home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-04 / pgp23src.zip / SRC / CRYPTO.C < prev    next >
C/C++ Source or Header  |  1993-06-11  |  99KB  |  3,114 lines

  1. /*    crypto.c  - Cryptographic routines for PGP.
  2.     PGP: Pretty Good(tm) Privacy - public key cryptography for the masses.
  3.  
  4.     (c) Copyright 1990-1992 by Philip Zimmermann.  All rights reserved.
  5.     The author assumes no liability for damages resulting from the use
  6.     of this software, even if the damage results from defects in this
  7.     software.  No warranty is expressed or implied.
  8.  
  9.     All the source code Philip Zimmermann wrote for PGP is available for
  10.     free under the "Copyleft" General Public License from the Free
  11.     Software Foundation.  A copy of that license agreement is included in
  12.     the source release package of PGP.  Code developed by others for PGP
  13.     is also freely available.  Other code that has been incorporated into
  14.     PGP from other sources was either originally published in the public
  15.     domain or was used with permission from the various authors.  See the
  16.     PGP User's Guide for more complete information about licensing,
  17.     patent restrictions on certain algorithms, trademarks, copyrights,
  18.     and export controls.  
  19.  
  20.      Modified: 12-Nov-92 HAJK
  21.      Add FDL stuff for VAX/VMS local mode. 
  22.     Reopen temporary files rather than create new version.
  23.  
  24.     Modified: 13-Dec-92 Derek Atkins <warlord@MIT.EDU)
  25.     Added Multiple Recipients
  26.  
  27.     Modified 25-Feb-93 Colin Plumb
  28.     Improved security of randseed.bin in strong_pseudorandom.
  29.     Thoroughly revamped make_random_ideakey.
  30.  
  31.     Modified  6-May-93 Colin Plumb
  32.     Changed to use the entry points in rsaglue.c.
  33. */
  34.  
  35. #include <ctype.h>
  36. #include <stdlib.h>
  37. #include <stdio.h>
  38. #include <string.h>
  39. #include <time.h>
  40.  
  41. #include "mpilib.h"
  42. #include "mpiio.h"
  43. #include "random.h"
  44. #include "idea.h"
  45. #include "crypto.h"
  46. #include "keymgmt.h"
  47. #include "keymaint.h"
  48. #include "mdfile.h"
  49. #include "fileio.h"
  50. #include "charset.h"
  51. #include "language.h"
  52. #include "pgp.h"
  53. #include "exitpgp.h"
  54. #include "zipup.h"
  55. #include "rsaglue.h"
  56.  
  57. #define ENCRYPT_IT FALSE    /* to pass to idea_file */
  58. #define DECRYPT_IT TRUE        /* to pass to idea_file */
  59.  
  60. #define    USE_LITERAL2
  61.  
  62.  
  63. /* This variable stores the md5 hash of the current file, if it is
  64.    available.  It is used in open_strong_pseudorandom. */
  65. static unsigned char md5buf[16];
  66.  
  67. /* This flag is set if the buffer above has been filled. */
  68. static char already_have_md5 = 0;
  69.  
  70.  
  71. /* Used by encryptfile */
  72. static int encryptkeyintofile(FILE *g, char *mcguffin, byte *keybuf,
  73.     char *keyfile, int ckp_length, int keys_used);
  74.  
  75. #ifdef  M_XENIX
  76. long time();
  77. #endif
  78.  
  79. /*--------------------------------------------------------------------------*/
  80.  
  81.  
  82. void CToPascal(char *s)
  83. {    /* "xyz\0" --> "\3xyz" ... converts C string to Pascal string */
  84.     int i,j;
  85.     j = string_length(s);
  86.     for (i=j; i!=0; i--)
  87.         s[i] = s[i-1];    /* move everything 1 byte to the right */
  88.     s[0] = j;        /* Pascal length byte at beginning */
  89. }    /* CToPascal */
  90.  
  91.  
  92. void PascalToC( char *s )
  93. {    /* "\3xyz" --> "xyz\0" ... converts Pascal string to C string */
  94.     int i,j;
  95.     for (i=0,j=((byte *) s)[0]; i<j; i++)
  96.         s[i] = s[i+1];    /* move everything 1 byte to the left */
  97.     s[i] = '\0';        /* append C string terminator */
  98. }    /* PascalToC */
  99.  
  100.  
  101. /* 
  102.     Note:  On MSDOS, the time() function calculates GMT as the local
  103.     system time plus a built-in timezone correction, which defaults to
  104.     adding 7 hours (PDT) in the summer, or 8 hours (PST) in the winter,
  105.     assuming the center of the universe is on the US west coast. Really--
  106.     I'm not making this up!  The only way to change this is by setting 
  107.     the MSDOS environmental variable TZ to reflect your local time zone,
  108.     for example "set TZ=MST7MDT".  This means add 7 hours during standard
  109.     time season, or 6 hours during daylight time season, and use MST and 
  110.     MDT for the two names of the time zone.  If you live in a place like 
  111.     Arizona with no daylight savings time, use "set TZ=MST7".  See the
  112.     Microsoft C function tzset().  Just in case your local software
  113.     environment is too weird to predict how to set environmental
  114.     variables for this, PGP also uses its own TZFIX variable in
  115.     config.pgp to optionally correct this problem further.  For example,
  116.     set TZFIX=-1 in config.pgp if you live in Colorado and the TZ
  117.     variable is undefined.
  118. */
  119.  
  120. word32 get_timestamp(byte *timestamp)
  121. /*    Return current timestamp as a byte array in internal byteorder,
  122.     and as a 32-bit word */
  123. {    word32 t;
  124.     t = time(NULL);    /* returns seconds since GMT 00:00 1 Jan 1970 */
  125.  
  126. #ifdef _MSC_VER
  127. #if (_MSC_VER == 700)
  128.     /*  Under MSDOS and MSC 7.0, time() returns elapsed time since
  129.      *  GMT 00:00 31 Dec 1899, instead of Unix's base date of 1 Jan 1970.
  130.      *  So we must subtract 70 years worth of seconds to fix this.
  131.      *  6/19/92  rgb 
  132.     */
  133. #define    LEAP_DAYS    (((unsigned long)70L/4)+1)
  134. #define CALENDAR_KLUDGE ((unsigned long)86400L * (((unsigned long)365L * 70L) + LEAP_DAYS))
  135.        t -= CALENDAR_KLUDGE;
  136. #endif
  137. #endif
  138.  
  139.     t += timeshift; /* timeshift derived from TZFIX in config.pgp */
  140.  
  141.     if (timestamp != NULL)
  142.     {    /* first, fill array in external byte order: */
  143.         put_word32(t, timestamp);
  144.         convert_byteorder(timestamp,4);    /* convert to internal byteorder */
  145.     }
  146.  
  147.     return(t);    /* return 32-bit timestamp integer */
  148. }    /* get_timestamp */
  149.  
  150.  
  151. static int date_ymd(word32 *tstamp, int *year, int *month, int *day)
  152. /*    Given timestamp as seconds elapsed since 1970 Jan 1 00:00:00,
  153.     returns year (1970-2106), month (1-12), day (1-31).
  154.     Not valid for dates after 2100 Feb 28 (no leap day that year).
  155.     Also returns day of week (0-6) as functional return.
  156. */
  157. {    word32 days,y;
  158.     int m,d,i;
  159.     static short mdays[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
  160.     days = (*tstamp)/(unsigned long)86400L;    /* day 0 is 1970/1/1 */
  161.     days -= 730L;    /* align days relative to 1st leap year, 1972 */
  162.     y = ((days*4)/(unsigned long)1461L);    /* 1972 is year 0 */
  163.     /* reduce to days elapsed since 1/1 last leap year: */
  164.     d = (int) (days - ((y/4)*1461L));
  165.     *year = (int)(y+1972);
  166.     for (i=0; i<48; i++)    /* count months 0-47 */
  167.     {    m = i % 12;
  168.         d -= mdays[m] + (i==1);    /* i==1 is the only leap month */
  169.         if (d < 0)
  170.         {    d += mdays[m] + (i==1);
  171.             break;
  172.         }
  173.     }
  174.     *month = m+1;
  175.     *day = d+1;
  176.     i = (int)((days-2) % (unsigned long)7L);    /* compute day of week 0-6 */
  177.     return(i);    /* returns weekday 0-6; 0=Sunday, 6=Saturday */
  178. }    /* date_ymd */
  179.  
  180.  
  181. char *cdate(word32 *tstamp)
  182. /*    Return date string, given pointer to 32-bit timestamp */
  183. {    int month,day,year;
  184.     static char datebuf[20];
  185.     if (*tstamp == 0)
  186.         return("          ");
  187.     (void) date_ymd(tstamp,&year,&month,&day);
  188.     sprintf(datebuf,"%4d/%02d/%02d", year, month, day);
  189.     return (datebuf);
  190. }    /* cdate */
  191.  
  192.  
  193. char *ctdate(word32 *tstamp)
  194. /*    Return date and time string, given pointer to 32-bit timestamp */
  195. {    int hours,minutes;
  196.     static char tdatebuf[40];
  197.     long seconds;
  198.     seconds = (*tstamp) % (unsigned long)86400L;    /* seconds past midnight today */
  199.     minutes = (int)((seconds+30L) / 60L);    /* round off to minutes past midnight */
  200.     hours = minutes / 60;            /* hours past midnight */
  201.     minutes = minutes % 60;            /* minutes past the hour */
  202.     sprintf(tdatebuf,"%s %02d:%02d GMT", cdate(tstamp), hours, minutes);
  203.     return (tdatebuf);
  204. }    /* ctdate */
  205.  
  206.  
  207.  
  208. /* Warn user he if key in keyfile at position fp of length pktlen, belonging
  209.  * to userid, is untrusted.  Return -1 if the user doesn't want to proceed.
  210.  */
  211. static int warn_signatures(char *keyfile, long fp, char *userid, boolean warn_only)
  212. {    FILE        *f;
  213.     long        fpusr;
  214.     int            usrpktlen;
  215.     byte        keyctrl;
  216.     int            trust_status = -1;
  217.  
  218.     keyctrl = KC_LEGIT_UNKNOWN;    /* Assume the worst */
  219.     if (getpubuserid (keyfile, fp, (byte *) userid, &fpusr, &usrpktlen, FALSE) >= 0)
  220.     {    f = fopen(keyfile, FOPRBIN);
  221.         fseek (f, fpusr+usrpktlen, SEEK_SET);
  222.         /* Read trust byte */
  223.         trust_status = read_trust(f, &keyctrl);
  224.         fseek(f, fp, SEEK_SET);
  225.         if (is_compromised(f))
  226.         {
  227.             CToPascal(userid);
  228.             fprintf(pgpout, "\n");
  229.             show_key(f, fp, 0);
  230.             fclose (f);
  231.             fprintf(pgpout, PSTR("\007\nWARNING:  This key has been revoked by its owner,\n\
  232. possibly because the secret key was compromised.\n"));
  233.             if (warn_only)
  234.             {    /* this is only for checking signatures */
  235.                 fprintf(pgpout, PSTR("This could mean that this signature is a forgery.\n"));
  236.                 return(1);
  237.             }
  238.             else
  239.             {    /* don't use it for encryption */
  240.                 fprintf(pgpout, PSTR("You cannot use this revoked key.\n"));
  241.                 return(-1);
  242.             }
  243.         }
  244.         fclose (f);
  245.     }
  246.     CToPascal(userid);
  247.     if ((keyctrl & KC_LEGIT_MASK) != KC_LEGIT_COMPLETE)
  248.     {    byte userid0[256];
  249.         PascalToC(userid);
  250.         strcpy ((char *) userid0, userid);
  251.         CToPascal(userid);
  252.  
  253.         if ((keyctrl & KC_LEGIT_MASK) == KC_LEGIT_UNKNOWN)
  254.             fprintf(pgpout,PSTR("\007\nWARNING:  Because this public key is not certified with a trusted\n\
  255. signature, it is not known with high confidence that this public key\n\
  256. actually belongs to: \"%s\".\n"), LOCAL_CHARSET((char *)userid0));
  257.  
  258.         if ((keyctrl & KC_LEGIT_MASK) == KC_LEGIT_UNTRUSTED)
  259.             fprintf(pgpout, PSTR("\007\nWARNING:  This public key is not trusted to actually belong to:\n\
  260. \"%s\".\n"), LOCAL_CHARSET((char *)userid0));
  261.  
  262.         if ((keyctrl & KC_LEGIT_MASK) == KC_LEGIT_MARGINAL)
  263.             fprintf(pgpout,PSTR("\007\nWARNING:  Because this public key is not certified with enough trusted\n\
  264. signatures, it is not known with high confidence that this public key\n\
  265. actually belongs to: \"%s\".\n"), LOCAL_CHARSET((char *)userid0));
  266.  
  267.         if (keyctrl & KC_WARNONLY)
  268.         {    /* KC_WARNONLY bit already set, user must have approved before. */
  269.             fprintf(pgpout, PSTR("But you previously approved using this public key anyway.\n"));
  270.         }
  271.  
  272.         if (!filter_mode && !batchmode && !warn_only && !(keyctrl & KC_WARNONLY))
  273.         {    fprintf(pgpout,PSTR("\nAre you sure you want to use this public key (y/N)? "));
  274.             if (!getyesno('n'))
  275.                 return(-1);
  276.             if (trust_status == 0 && (f = fopen(keyfile, FOPRWBIN)) != NULL)
  277.             {    fseek (f, fpusr+usrpktlen, SEEK_SET);
  278.                 keyctrl |= KC_WARNONLY;
  279.                 write_trust(f, keyctrl);
  280.                 fclose(f);
  281.             }
  282.         }
  283.     }
  284.     return(0);
  285. }    /* warn_signatures */
  286.  
  287.  
  288. boolean legal_ctb(byte ctb)
  289. {    /* Used to determine if nesting should be allowed. */
  290.     boolean legal;
  291.     byte ctbtype;
  292.     if (!is_ctb(ctb))        /* not even a bonafide CTB */
  293.         return(FALSE);
  294.     /* Sure hope CTB internal bit definitions don't change... */
  295.     ctbtype = (ctb & CTB_TYPE_MASK) >> 2;
  296.     /* Only allow these CTB types to be nested... */
  297.     legal = (
  298.             (ctbtype==CTB_PKE_TYPE)
  299.         ||    (ctbtype==CTB_SKE_TYPE)
  300.         ||    (ctbtype==CTB_CERT_SECKEY_TYPE)
  301.         ||    (ctbtype==CTB_CERT_PUBKEY_TYPE)
  302.         ||    (ctbtype==CTB_LITERAL_TYPE)
  303.         ||    (ctbtype==CTB_LITERAL2_TYPE)
  304.         ||    (ctbtype==CTB_COMPRESSED_TYPE)
  305.         ||  (ctbtype==CTB_CKE_TYPE)
  306.          );
  307.     return(legal);
  308. }    /* legal_ctb */
  309.  
  310.  
  311. /* Return nonzero if val doesn't match checkval, after printing a
  312.  * warning.
  313.  */
  314. int
  315. version_error(int val, int checkval)
  316. {    if (val != checkval)
  317.     {    fprintf (pgpout, PSTR(
  318. "\n\007Unsupported packet format - you need a newer version of PGP for this file.\n"));
  319.         return(1);
  320.     }
  321.     return(0);
  322. }
  323.  
  324. /*-------------------------------------------------------------------------*/
  325.  
  326. #define RAND_PREFIX_LENGTH 8    /* Length of IV for IDEA encryption */
  327.  
  328. int seedfile_exists(void)
  329. /*
  330.     If the file randseed.bin does not exist, this returns 0 and
  331.     schedules the appropriate number of random bytes for later
  332.     collection from the keyboard.
  333.  */
  334. {    char seedfile[MAX_PATH];    /* Random seed filename */
  335.  
  336.     buildfilename(seedfile,RANDSEED_FILENAME);
  337.     if (file_exists(seedfile))
  338.         return 1;    /* True */
  339.     randaccum_later(8*(IDEAKEYSIZE+RAND_PREFIX_LENGTH));
  340.     return 0;
  341. }
  342.  
  343. void create_seedfile(void)
  344. /*
  345.     Create the seedfile, from the random bits that seedfile_exists
  346.     buffered for accumulation.  "randseed.bin" is used to generate
  347.     cryptographically strong pseudorandom numbers for session keys.
  348.  */
  349. {    char seedfile[MAX_PATH];    /* Random seed filename */
  350.     FILE *f;
  351.     byte randbuf[IDEAKEYSIZE+RAND_PREFIX_LENGTH];
  352.     int i;
  353.  
  354.     buildfilename(seedfile,RANDSEED_FILENAME);
  355.  
  356.     f = fopen(seedfile,FOPWBIN);    /* open for writing binary */
  357.     if (f==NULL)    /* failed to create seedfile */
  358.         return;    /* error: no random number seed file available */
  359.     fprintf(pgpout,PSTR("Initializing random seed file..."));
  360. /* This is not part of the string above because it was changed after the 2.2
  361.    release translations were started.  It should be cleaned up eventually. */
  362.     fputc('\n', pgpout);
  363.     for (i=1; i<sizeof(randbuf); i++)
  364.         randbuf[i] ^= randombyte();
  365. #ifdef VMS
  366.     fseek (f, 0, SEEK_SET);
  367. #endif
  368.     fwrite(randbuf,1,sizeof(randbuf),f);
  369.     fclose(f);
  370.     burn(randbuf);        /* Not terribly sensitive, but... */
  371. }
  372.  
  373. static int open_strong_pseudorandom(byte key[16], byte buf[24])
  374. /* Read the randseed.bin file, encrypting it on the way with the given
  375.    key.  It is intended that this key is the md5 of the message to be
  376.    encrypted, which is unpredictable to a would-be attacker who does
  377.    not posess the message.  This is simply a way to get some "random"
  378.    bytes without a random number source.  This "prewash" attempts to
  379.    reduce the value of a captured randseed.bin file. 
  380.    Returns the length of the resultant data, or -1 in case of error. */
  381. {    char seedfile[MAX_PATH];    /* Random seed filename */
  382.     FILE *f;
  383.     static word16 iv0[4] = {0, 0, 0, 0};
  384.     
  385.     buildfilename(seedfile,RANDSEED_FILENAME);
  386.  
  387.     if (!file_exists(seedfile))    /* No seed file - not available. */
  388.         return(-1);
  389.     f = fopen(seedfile,FOPRBIN);    /* open for reading binary */
  390.     if (f==NULL)    /* did open fail? */
  391.         return(-1);    /* error: no random number seed file available */
  392.     /* read IDEA random generator key */
  393.     if (fread(buf,1,sizeof(buf),f) < sizeof(buf))    /* empty file? */
  394.     {    /* Empty or nearly empty file means don't use it. */
  395.         fclose(f);
  396.         return(-1);    /* error: no random number seed file available */
  397.     }
  398.     initcfb_idea(iv0, key, FALSE);
  399.     ideacfb(buf, 24);
  400.     burn(iv0);
  401.     return 24;
  402. }
  403.  
  404. static int close_strong_pseudorandom(byte ideakey[IDEAKEYSIZE+RAND_PREFIX_LENGTH])
  405. /*    Using the same key and initial vector that is used to encrypt the
  406.     user's message, encrypt some pseudorandom bytes to produce the
  407.     new randseed.bin.  The hope is that this "postwash" renders it is
  408.     at least as hard to derive old session keys from randseed.bin as it
  409.     is to crack the the message directly. 
  410.         Note that this function leaves idearand() running; you must
  411.     call close_idearand() separately. */
  412.  
  413. {    static word16 iv0[4] = {0, 0, 0, 0};
  414.     byte buf[IDEAKEYSIZE+RAND_PREFIX_LENGTH];
  415.     char seedfile[MAX_PATH];    /* Random seed filename */
  416.     FILE *f;
  417.     int i;
  418.     
  419.     buildfilename(seedfile,RANDSEED_FILENAME);
  420.     f = fopen(seedfile,FOPWBIN);    /* open for writing binary */
  421.     if (f==NULL)    /* did open fail? */
  422.         return(-1);    /* error: no random number seed file available */
  423.     initcfb_idea(iv0, ideakey, FALSE);        /* Start encryption */
  424.     memcpy(buf, ideakey+IDEAKEYSIZE, RAND_PREFIX_LENGTH);
  425.     memcpy(buf+RAND_PREFIX_LENGTH, buf+RAND_PREFIX_LENGTH-2, 2);
  426.     ideacfb(buf, RAND_PREFIX_LENGTH+2);    /* Feed IV through */
  427.  
  428.     for (i = 0; i < sizeof(buf); i++)    /* Get message to encrypt */
  429.         buf[i] = idearand();
  430.     ideacfb(buf, sizeof(buf));        /* Encrypt it */
  431. #ifdef VMS
  432.     fseek (f, 0, SEEK_SET);
  433. #endif
  434.     /* Now at start of file again */
  435.     i = fwrite(buf,1,sizeof(buf),f);    /* Write it out */
  436.     fclose(f);
  437.     burn(iv0);    /* Burn all data */
  438.     burn(buf);
  439.     close_idea();
  440.  
  441.     if (i != sizeof(buf))
  442.         return -1;    /* error */
  443.     return i;
  444. }
  445.  
  446. static int make_random_ideakey(byte key[IDEAKEYSIZE+RAND_PREFIX_LENGTH])
  447. /*    Make a random IDEA key.  Returns its length (the constant 16).
  448.     It also generates a random IV, which is placed in the key array
  449.     after the key proper, but is not counted in the length.
  450.     Reads IDEA random key and random number seed from file, cranks the
  451.     seed through the idearand strong pseudorandom number generator,
  452.     and writes them back out.  This is used for generation of
  453.     cryptographically strong pseudorandom numbers.  This is mainly to
  454.     save the user the trouble of having to type in lengthy keyboard
  455.     sequences for generation of truly random numbers every time we want
  456.     to make a random session key.  This pseudorandom generator will only
  457.     work if the file containing the random seed exists and is not empty.
  458.     If this is not the case, it will be automatically created.
  459. */
  460. {
  461.     word32 tstamp;
  462.     int count;
  463.  
  464.     if (open_strong_pseudorandom(md5buf, key) < 0)
  465.     {
  466.         fprintf(pgpout,PSTR("Preparing random session key..."));
  467.  
  468.         randaccum((IDEAKEYSIZE+RAND_PREFIX_LENGTH)*8);
  469.              /* get some random key bits */
  470.  
  471.         for (count = 0; count < IDEAKEYSIZE+RAND_PREFIX_LENGTH; count++)
  472.             key[count] = randombyte();
  473.     }
  474.  
  475.     get_timestamp((byte *)&tstamp);
  476.     init_idearand(key, key+IDEAKEYSIZE, tstamp);
  477.  
  478. /* Generate a good random IDEA key and initial vector */
  479. /* If we have no random bytes, the randombyte() part will be useless */
  480.     count = IDEAKEYSIZE+RAND_PREFIX_LENGTH;
  481.     while (count--)
  482.         key[count] = idearand() ^ try_randombyte();
  483.  
  484. /* Write out a new randseed.bin */
  485.     close_strong_pseudorandom(key);
  486.     
  487.     return IDEAKEYSIZE;
  488. }
  489.  
  490.  
  491. word32 getpastlength(byte ctb, FILE *f)
  492. /*    Returns the length of a packet according to the CTB and
  493.     the length field. */
  494. {    word32 length;
  495.     unsigned int llength;    /* length of length */
  496.     byte buf[8];
  497.  
  498.     fill0(buf,sizeof(buf));
  499.     length = 0L;
  500.     /* Use ctb length-of-length field... */
  501.     llength = ctb_llength(ctb);    /* either 1, 2, 4, or 8 */
  502.     if (llength==8)        /* 8 means no length field, assume huge length */
  503.         return(-1L);    /* return huge length */
  504.  
  505.     /* now read in the actual length field... */
  506.     if (fread((byteptr) buf,1,llength,f) < llength)
  507.         return (-2L); /* error -- read failure or premature eof */
  508.     /* convert length from external byteorder... */
  509.     if (llength==1)
  510.         length = (word32) buf[0];
  511.     if (llength==2)
  512.         length = (word32) fetch_word16(buf);
  513.     if (llength==4)
  514.         length = fetch_word32(buf);
  515.     return(length);
  516. }    /* getpastlength */
  517.  
  518.  
  519. /* Write a CTB with the appropriate length field.  If big is true,
  520.  * always use a four-byte length field.
  521.  */
  522. void write_ctb_len (FILE *f, byte ctb_type, word32 length, boolean big)
  523. {
  524.     int        llength, llenb;
  525.     byte    ctb;
  526.     byte    buf[4];
  527.  
  528.     if (big || (length > 0xFFFFL))
  529.     {    llength = 4;
  530.         llenb = 2;
  531.     }
  532.     else if ((word16)length > 0xFF)
  533.     {    llength = 2;
  534.         llenb = 1;
  535.     }
  536.     else
  537.     {    llength = 1;
  538.         llenb = 0;
  539.     }
  540.     ctb = CTB_BYTE(ctb_type, llenb);
  541.     fwrite( &ctb, 1, 1, f );
  542.     /* convert length to external byteorder... */
  543.     if (llength==1)
  544.         buf[0] = length;
  545.     if (llength==2)
  546.         put_word16((word16) length, buf);
  547.     if (llength==4)
  548.         put_word32(length, buf);
  549.     fwrite( buf, 1, llength, f );
  550. } /* write_ctb_len */
  551.  
  552.  
  553. static
  554. int idea_file(byte *ideakey, boolean decryp, FILE *f, FILE *g, word32 lenfile)
  555. /*    Use IDEA in cipher feedback (CFB) mode to encrypt or decrypt a file. 
  556.     The encrypted material starts out with a 64-bit random prefix, which
  557.     serves as an encrypted random CFB initialization vector, and
  558.     following that is 16 bits of "key check" material, which is a
  559.     duplicate of the last 2 bytes of the random prefix.  Encrypted key
  560.     check bytes detect if correct IDEA key was used to decrypt ciphertext.
  561. */
  562. {    int count, status = 0;
  563.     word16 iv[4];
  564.     extern byte textbuf[DISKBUFSIZE];
  565. #define RAND_PREFIX_LENGTH 8
  566.  
  567.     /* init CFB key */
  568.     fill0(iv,sizeof(iv));    /* define initialization vector IV as 0 */
  569.     initcfb_idea(iv,ideakey,decryp);
  570.  
  571.     if (!decryp)    /* encrypt-- insert key check bytes */
  572.     {    /* There is a random prefix followed by 2 key check bytes */
  573.  
  574.         memcpy(textbuf, ideakey+IDEAKEYSIZE, RAND_PREFIX_LENGTH);
  575.         /* key check bytes are simply duplicates of final 2 random bytes */
  576.         textbuf[RAND_PREFIX_LENGTH] = textbuf[RAND_PREFIX_LENGTH-2];
  577.         textbuf[RAND_PREFIX_LENGTH+1] = textbuf[RAND_PREFIX_LENGTH-1];
  578.  
  579.         ideacfb(textbuf,RAND_PREFIX_LENGTH+2);
  580.         fwrite(textbuf,1,RAND_PREFIX_LENGTH+2,g);
  581.     }
  582.     else    /* decrypt-- check for key check bytes */
  583.     {    /* See if the redundancy is present after the random prefix */
  584.         count = fread(textbuf,1,RAND_PREFIX_LENGTH+2,f);
  585.         lenfile -= count;
  586.         if (count==(RAND_PREFIX_LENGTH+2))
  587.         {    ideacfb(textbuf,RAND_PREFIX_LENGTH+2);
  588.             if ((textbuf[RAND_PREFIX_LENGTH] != textbuf[RAND_PREFIX_LENGTH-2])
  589.                 || (textbuf[RAND_PREFIX_LENGTH+1] != textbuf[RAND_PREFIX_LENGTH-1]))
  590.             {    status = -2;        /* bad key error */
  591.             }
  592.         }
  593.         else    /* file too short for key check bytes */
  594.             status = -3;        /* error of the weird kind */
  595.     }
  596.  
  597.  
  598.     /* read and write the whole file in CFB mode... */
  599.     count = (lenfile < DISKBUFSIZE) ? (int)lenfile : DISKBUFSIZE;
  600.     while (count && status == 0)
  601.     {    if ((count = fread(textbuf,1,count,f)) <= 0)
  602.         {    status = -3;
  603.             break;
  604.         }
  605.         lenfile -= count;
  606.         ideacfb(textbuf,count);
  607.         if (fwrite(textbuf,1,count,g) != count)
  608.             status = -3;
  609.         count = (lenfile < DISKBUFSIZE) ? (int)lenfile : DISKBUFSIZE;
  610.     }
  611.  
  612.     close_idea();    /* Clean up data structures */
  613.     burn(iv);        /* burn sensitive data on stack */
  614.     burn(textbuf);    /* burn sensitive data on stack */
  615.     return(status);    /* should always take normal return */
  616. }    /* idea_file */
  617.  
  618.  
  619. /* Checksum maintained as a running sum by read_mpi and write_mpi.
  620.  * The checksum is maintained based on the plaintext values being
  621.  * read and written.  To use it, store a 0 to it before doing a set
  622.  * of read_mpi's or write_mpi's.  Then read it aftwerwards.
  623.  */
  624. word16    mpi_checksum;
  625.  
  626. int read_mpi(unitptr r, FILE *f, boolean adjust_precision, boolean scrambled)
  627. /*    Read a mutiprecision integer from a file.
  628.     adjust_precision is TRUE iff we should call set_precision to the 
  629.     size of the number read in.
  630.     scrambled is TRUE iff field is encrypted (protects secret key fields).
  631.     Returns the bitcount of the number read in, or returns a negative
  632.     number if an error is detected.
  633. */
  634. {    byte buf[MAX_BYTE_PRECISION+2];
  635.     unsigned int count;
  636.     word16 bytecount,bitcount;
  637.  
  638.     mp_init(r,0);
  639.  
  640.     if ((count = fread(buf,1,2,f)) < 2)
  641.         return (-1); /* error -- read failure or premature eof */
  642.  
  643.     bitcount = fetch_word16(buf);
  644.     if (bits2units(bitcount) > global_precision)
  645.         return(-1);    /* error -- possible corrupted bitcount */
  646.  
  647.     bytecount = bits2bytes(bitcount);
  648.  
  649.     count = fread(buf+2,1,bytecount,f);
  650.     if (count < bytecount)
  651.         return(-1);    /* error -- premature eof */
  652.  
  653.     if (scrambled)    /* decrypt the field */
  654.         ideacfb(buf+2,bytecount);
  655.  
  656.     /* Update running checksum, in case anyone cares... */
  657.     mpi_checksum += checksum (buf, bytecount+2);
  658.  
  659.     /*    We assume that the bitcount prefix we read is an exact
  660.         bitcount, not rounded up to the next byte boundary.
  661.         Otherwise we would have to call mpi2reg, then call
  662.         countbits, then call set_precision, then recall mpi2reg
  663.         again.
  664.     */
  665.     if (adjust_precision && bytecount)
  666.     {    /* set the precision to that specified by the number read. */
  667.         if (bitcount > MAX_BIT_PRECISION-SLOP_BITS)
  668.             return(-1);
  669.         set_precision(bits2units(bitcount+SLOP_BITS));
  670.         /* Now that precision is optimally set, call mpi2reg */
  671.     }
  672.  
  673.     if (mpi2reg(r,buf) == -1)    /* convert to internal format */
  674.         return(-1);
  675.     burn(buf);    /* burn sensitive data on stack */
  676.     return (bitcount);
  677. }    /* read_mpi */
  678.  
  679.  
  680.  
  681. void write_mpi(unitptr n, FILE *f, boolean scrambled)
  682. /*    Write a multiprecision integer to a file.
  683.     scrambled is TRUE iff we should scramble field on the way out,
  684.     which is used to protect secret key fields.
  685. */
  686. {    byte buf[MAX_BYTE_PRECISION+2];
  687.     short bytecount;
  688.     bytecount = reg2mpi(buf,n);
  689.     mpi_checksum += checksum (buf, bytecount+2);
  690.     if (scrambled)  /* encrypt the field, skipping over the bitcount */
  691.         ideacfb(buf+2,bytecount);
  692.     fwrite(buf,1,bytecount+2,f); 
  693.     burn(buf);    /* burn sensitive data on stack */
  694. }    /* write_mpi */
  695.  
  696.  
  697. /*======================================================================*/
  698.  
  699.  
  700. int get_header_info_from_file(char *infile,  byte *header, int count)
  701. /*    Reads the first count bytes from infile into header. */
  702. {    FILE *f;
  703.     fill0(header,count);
  704.     /* open file f for read, in binary (not text) mode...*/
  705.     if ((f = fopen(infile,FOPRBIN)) == NULL)
  706.         return(-1);
  707.     /* read Cipher Type Byte, and maybe more */
  708.     count = fread(header,1,count,f);
  709.     fclose(f);
  710.     return(count);    /* normal return */
  711. }    /* get_header_info_from_file */
  712.  
  713.  
  714. /* System clock must be broken if it isn't past this date: */
  715. #define REASONABLE_DATE ((unsigned long) 0x27804180L)  /* 91 Jan 01 00:00:00 */
  716.  
  717.  
  718. static
  719. int make_signature_certificate(byte *certificate, MD5_CTX *MD, byte class,
  720.     unitptr e, unitptr d, unitptr p, unitptr q, unitptr u, unitptr n)
  721. /*    Constructs a signed message digest in a signature certificate.
  722.     Returns total certificate length in bytes, or returns negative
  723.     error status.
  724. */
  725. {
  726.     byte inbuf[MAX_BYTE_PRECISION], outbuf[MAX_BYTE_PRECISION];
  727.     int i, j, certificate_length, blocksize,bytecount;
  728.     word16 ske_length;
  729.     word32 tstamp; byte *timestamp = (byte *) &tstamp;
  730.     byte keyID[KEYFRAGSIZE];
  731.     byte val;
  732.     int mdlen = 5;    /* length of class plus timestamp, for adding to MD */
  733.  
  734.     /*    Note that RSA key must be at least big enough to encipher a
  735.         complete message digest packet in a single RSA block. */
  736.  
  737.         blocksize = countbytes(n)-1;    /* size of a plaintext block */
  738.         if (blocksize < 31)
  739.         {    fprintf(pgpout,"\n\007Error: RSA key length must be at least 256 bits.\n");
  740.             return(-1);
  741.         }
  742.  
  743.         get_timestamp(timestamp);    /* Timestamp when signature was made */
  744.         if (tstamp < REASONABLE_DATE) /* complain about bad time/date setting */
  745.         {    fprintf(pgpout,PSTR("\n\007Error: System clock/calendar is set wrong.\n"));
  746.             return(-1);
  747.         }
  748.         convert_byteorder(timestamp,4); /* convert to external form */
  749.  
  750.         /* Finish off message digest calculation with this information */
  751.     MD_addbuffer (MD, &class, 1, 0);
  752.     MD_addbuffer (MD, timestamp, 4, md5buf);
  753. /* We wrote the digest to a static variable because we want to keep it around
  754.    for random number generation later.   Also make a note of that fact. */
  755.     already_have_md5 = 1;
  756.  
  757.     if (!quietmode)
  758.     {    fprintf(pgpout,PSTR("Just a moment..."));    /* RSA will take a while. */
  759.         fflush(pgpout);
  760.     }
  761.  
  762.     /* do RSA signature calculation: */
  763.     rsa_private_encrypt((unitptr)outbuf, md5buf, sizeof(md5buf),
  764.         e, d, p, q, u, n);
  765.  
  766.     /* bytecount does not include the 2 prefix bytes */
  767.     bytecount = reg2mpi(outbuf,(unitptr)outbuf); /* convert to external format */
  768.     /*    outbuf now contains a message digest in external byteorder 
  769.         form.  Now make a complete signature certificate from this.
  770.         (Note that the first two bytes of md5buf are used below as
  771.         part of the certificate.)
  772.     */
  773.  
  774.     certificate_length = 0;
  775.  
  776.     /* SKE is Secret Key Encryption (signed).  Append CTB for signed msg. */
  777.     certificate[certificate_length++] = CTB_SKE;
  778.  
  779.     /* SKE packet length does not include itself or CTB prefix: */
  780.     ske_length = 1 + 1     /* version and mdlen byte */
  781.                 + mdlen        /* class, timestamp and validation period */ 
  782.                 + KEYFRAGSIZE + 1 + 1    /* Key ID and 2 algorithm bytes */
  783.                 + 2 + bytecount+2;    /* 2 MD bytes and RSA MPI w/bitcount */
  784.     put_word16((word16) ske_length, certificate+certificate_length);
  785.     certificate_length+=2;    /* advance past word */
  786.  
  787.     certificate[certificate_length++] = VERSION_BYTE;
  788.  
  789.     /* Begin fields that are included in MD calculation... */
  790.  
  791.     certificate[certificate_length++] =  mdlen;    /* mdlen is length of MD-extras */
  792.  
  793.     certificate[certificate_length++] =  class & 0xff;
  794.     mdlen--;    /* assume class byte always present */
  795.  
  796.     /* timestamp already in external format */
  797.     if (mdlen>0)
  798.     {    for (j=0; j<SIZEOF_TIMESTAMP; j++)
  799.         {    certificate[certificate_length++] =  timestamp[j];
  800.             mdlen--;
  801.         }
  802.     }
  803.  
  804.     /* if any bytes remain in mdlen, assume it's the validation period */
  805.     if (mdlen>0)
  806.     {    val = 0;    /* Validation period */
  807.         put_word16(val, certificate+certificate_length);
  808.         certificate_length+=2;    /* advance past word */
  809.         mdlen-=2;
  810.     }
  811.     /* hopefully, mdlen is now zero.  */
  812.  
  813.     /* ...end of fields that are included in MD calculation */
  814.  
  815.     /* Now append keyID... */
  816.     extract_keyID(keyID, n);    /* gets keyID */
  817.     for (i=0; i<KEYFRAGSIZE; i++)
  818.         certificate[certificate_length++] = keyID[i];
  819.  
  820.     certificate[certificate_length++] = RSA_ALGORITHM_BYTE;
  821.     certificate[certificate_length++] = MD5_ALGORITHM_BYTE;
  822.  
  823.     /* Now append first two bytes of message digest */
  824.     certificate[certificate_length++] = md5buf[0];
  825.     certificate[certificate_length++] = md5buf[1];;
  826.  
  827.     /* Now append the RSA-signed message digest packet: */
  828.     for (i=0; i<bytecount+2; i++)
  829.         certificate[certificate_length++] = outbuf[i];
  830.  
  831.     if (!quietmode)
  832.         fputc('.',pgpout);    /* Signal RSA signature completion. */
  833.  
  834.     burn(inbuf);    /* burn sensitive data on stack */
  835.     burn(outbuf);    /* burn sensitive data on stack */
  836.  
  837.     return(certificate_length);    /* return length of certificate in bytes */
  838.  
  839. }    /* make_signature_certificate */
  840.  
  841.  
  842. #ifdef VMS
  843. void write_litlocal(FILE *g, char *fdl, short fdl_len)
  844. {
  845. /*
  846.  * Local mode VMS, we write out the word VMS to say who owns the data then we follow
  847.  * that with the file's FDL generated earlier by fdl_generate(). This FDL is preceded
  848.  * by a sixteen bit size. The file follows.
  849.  */
  850.     fputc('\0', g); /* Kludge for null literal file name (supplied by FDL) */
  851.     fputs("VMS ", g);
  852.     fwrite(&fdl_len, 2, 1, g); /* Byte order *not* important, only VMS reads this!*/
  853.     fwrite(fdl, 1, fdl_len, g);
  854. }
  855. #endif /* VMS */
  856.  
  857. /*======================================================================*/
  858.  
  859.  
  860. int signfile(boolean nested, boolean separate_signature,
  861.         char *mcguffin, char *infile, char *outfile,
  862.         char lit_mode, char *literalfile)
  863. /*    Write an RSA-signed message digest of input file to specified
  864.     output file, and append input file to output file.
  865.     separate_signature is TRUE iff we should not append the 
  866.     plaintext to the output signature certificate.
  867.     If lit_mode is MODE_TEXT, we know the infile is in canonical form.
  868.     We create a CTB_LITERAL packet for the plaintext data.
  869. */
  870. {    
  871.     FILE *f;
  872.     FILE *g;
  873.     int certificate_length;    /* signature certificate length */
  874.     byte certificate[MAX_SIGCERT_LENGTH];
  875.     char lfile[MAX_PATH];
  876.     byte signature_class;
  877. #ifdef VMS
  878.     char *fdl;
  879.     short fdl_len;
  880. #endif /* VMS */
  881.  
  882.  
  883.     {    /* temporary scope for some buffers */
  884.         word32 tstamp; byte *timestamp = (byte *) &tstamp;        /* key certificate timestamp */
  885.         byte userid[256];
  886.         char keyfile[MAX_PATH];
  887.         int status;
  888.         MD5_CTX MD;
  889.         byte keyID[KEYFRAGSIZE];
  890.         unit n[MAX_UNIT_PRECISION], e[MAX_UNIT_PRECISION], d[MAX_UNIT_PRECISION];
  891.         unit p[MAX_UNIT_PRECISION], q[MAX_UNIT_PRECISION], u[MAX_UNIT_PRECISION];
  892.  
  893.         set_precision(MAX_UNIT_PRECISION);    /* safest opening assumption */
  894.  
  895.         if (verbose)
  896.             fprintf(pgpout,"signfile: infile = '%s', outfile = '%s', mode = '%c', literalfile = '%s'\n",
  897.             infile,outfile,lit_mode,literalfile);
  898.  
  899.         if (MDfile(&MD, infile) < 0)
  900.             return(-1);    /* problem with input file.  error return */
  901.  
  902.         userid[0] = '\0';
  903.         if (mcguffin)
  904.             strcpy((char *) userid,mcguffin);    /* Who we are looking for */
  905.  
  906.         if (getsecretkey(0, NULL, NULL, timestamp, NULL, NULL,
  907.                          userid, n, e, d, p, q, u) < 0)
  908.             return(-1);    /* problem with secret key file. error return. */
  909.  
  910.         extract_keyID(keyID, n);
  911.         buildfilename(keyfile,PUBLIC_KEYRING_FILENAME); /* use default pathname */
  912.         if ((status = getpublickey(GPK_SHOW|GPK_NORVK, keyfile, NULL, NULL, keyID,
  913.                 timestamp, userid, n, e)) < 0)
  914.             return(-1);    /* problem with public key file. error return. */
  915.  
  916.         if (lit_mode==MODE_TEXT) signature_class = SM_SIGNATURE_BYTE;
  917.         else signature_class = SB_SIGNATURE_BYTE;
  918.  
  919.         certificate_length = make_signature_certificate(certificate, &MD,
  920.             signature_class, e, d, p, q, u, n);
  921.         if (certificate_length < 0)
  922.             return(-1);    /* error return from make_signature_certificate() */
  923.     }    /* end of scope for some buffers */
  924.  
  925.     /* open file f for read, in binary (not text) mode...*/
  926. #ifdef VMS
  927.     if (lit_mode == MODE_LOCAL) {
  928.         if (!(fdl_generate(infile, &fdl, &fdl_len ) & 01)) {
  929.         fprintf(pgpout,PSTR("\n\007Can't open input plaintext file '%s'\n"),infile);
  930.         return(-1);
  931.         }
  932.     }
  933. #endif /* VMS */
  934.     if ((f = fopen(infile,FOPRBIN)) == NULL)
  935.     {    fprintf(pgpout,PSTR("\n\007Can't open plaintext file '%s'\n"),infile);
  936.         return(-1);
  937.     }
  938.  
  939.     /* open file g for write, in binary (not text) mode...*/
  940.     if ((g = fopen(outfile,FOPWBIN)) == NULL)
  941.     {    fprintf(pgpout,PSTR("\n\007Can't create signature file '%s'\n"),outfile);
  942.         fclose(f);
  943.         return(-1);
  944.     }
  945.  
  946.     /* write out certificate record to outfile ... */
  947.     fwrite(certificate,1,certificate_length,g);
  948.  
  949.     if (literalfile == NULL)
  950.     {    /* Put in a zero byte to indicate no filename */
  951.         lfile[0] = '\0';
  952.     }
  953.     else
  954.     {    strcpy( lfile, literalfile );
  955.         file_to_canon( lfile );
  956.         CToPascal( lfile );
  957.     }
  958.  
  959.     if (!separate_signature)
  960.     {    if (!nested)
  961.         {    word32 flen = fsize(f);
  962.             word32 dummystamp = 0;
  963.             if (lit_mode == MODE_LOCAL)
  964. #ifdef VMS
  965.                 write_ctb_len (g, CTB_LITERAL2_TYPE,
  966.                         flen + fdl_len + sizeof(fdl_len) + 6, TRUE);
  967. #else
  968.                 /* debug check: should never get here */
  969.                 fprintf(pgpout, "signfile: invalid mode\n");
  970. #endif
  971.             else
  972. #ifdef USE_LITERAL2
  973.                 write_ctb_len (g, CTB_LITERAL2_TYPE, flen + (unsigned char) lfile[0] + 6, FALSE);
  974. #else
  975.                 write_ctb_len (g, CTB_LITERAL_TYPE, flen, FALSE);
  976. #endif /* USE_LITERAL2 */
  977.             fwrite ( &lit_mode, 1, 1, g );    /*    write lit_mode */
  978.             if (lit_mode == MODE_LOCAL) {    
  979. #ifdef VMS
  980.                 write_litlocal( g, fdl, fdl_len);
  981.                 free(fdl);
  982. #endif /* VMS */
  983.             } else {
  984.                 /* write literalfile name */
  985.                 fwrite (lfile, 1, (unsigned char) lfile[0]+1, g);
  986.                 /* Dummy file creation timestamp */
  987.                 fwrite ( &dummystamp, 1, sizeof(dummystamp), g);
  988.             }
  989.         }
  990.         copyfile(f,g,-1L);    /* copy rest of file from file f to g */
  991.     }
  992.  
  993.     fclose(f);
  994.     if (write_error(g))
  995.     {    fclose(g);
  996.         return(-1);
  997.     }
  998.     fclose(g);
  999.     return(0);    /* normal return */
  1000.  
  1001. }    /* signfile */
  1002.  
  1003.  
  1004. /*======================================================================*/
  1005.  
  1006.  
  1007. int compromise(byte *keyID, char *keyfile)
  1008. {    
  1009.     FILE *f, *g;
  1010.     byte ctb;    /* Cipher Type Byte */
  1011.     int certificate_length;    /* signature certificate length */
  1012.     byte certificate[MAX_SIGCERT_LENGTH];
  1013.     word32 tstamp; byte *timestamp = (byte *) &tstamp;
  1014.     byte userid[256];
  1015.     unit n[MAX_UNIT_PRECISION], e[MAX_UNIT_PRECISION];
  1016.     MD5_CTX MD;
  1017.     unit d[MAX_UNIT_PRECISION];
  1018.     unit p[MAX_UNIT_PRECISION], q[MAX_UNIT_PRECISION], u[MAX_UNIT_PRECISION];
  1019.     long fp, insertpos;
  1020.     int pktlen;
  1021.     int prec;
  1022.     char *scratchf;
  1023.  
  1024.     setoutdir(keyfile);
  1025.     scratchf = tempfile(0);
  1026.  
  1027.     if (getsecretkey(0, NULL, keyID, timestamp, NULL, NULL,
  1028.                      userid, n, e, d, p, q, u) < 0)
  1029.         return(-1);    /* problem with secret key file. error return. */
  1030.  
  1031.     if (getpublickey(0, keyfile, &fp, &pktlen, keyID,
  1032.             timestamp, userid, n, e) < 0)
  1033.         return(-1);
  1034.  
  1035.     /* open file f for read, in binary (not text) mode...*/
  1036.     if ((f = fopen(keyfile,FOPRBIN)) == NULL)
  1037.     {    fprintf(pgpout,PSTR("\n\007Can't open key ring file '%s'\n"),keyfile);
  1038.         return(-1);
  1039.     }
  1040.  
  1041.     fseek (f, fp+pktlen, SEEK_SET);
  1042.     nextkeypacket(f, &ctb);
  1043.     if (ctb == CTB_KEYCTRL)
  1044.     {    insertpos = ftell(f);
  1045.         nextkeypacket(f, &ctb);
  1046.     }
  1047.     else
  1048.         insertpos = fp + pktlen;
  1049.  
  1050.     if (is_ctb_type(ctb, CTB_SKE_TYPE))
  1051.     {
  1052.         fprintf(pgpout, PSTR("This key has already been revoked.\n"));
  1053.         fclose(f);
  1054.         return(-1);
  1055.     }
  1056.  
  1057.     prec = global_precision;
  1058.     set_precision(MAX_UNIT_PRECISION);    /* safest opening assumption */
  1059.  
  1060.     fseek(f, fp, SEEK_SET);
  1061.     /* Calculate signature */
  1062.     if (MDfile0_len(&MD, f, pktlen) < 0)
  1063.     {    fclose(f);
  1064.         return(-1);    /* problem with input file.  error return */
  1065.     }
  1066.     set_precision(prec);
  1067.  
  1068.     certificate_length = make_signature_certificate(certificate, &MD,
  1069.         KC_SIGNATURE_BYTE, e, d, p, q, u, n);
  1070.     if (certificate_length < 0)
  1071.     {    fclose(f);
  1072.         return(-1);    /* error return from make_signature_certificate() */
  1073.     }
  1074.  
  1075.  
  1076.     /* open file g for write, in binary (not text) mode...*/
  1077.     if ((g = fopen(scratchf,FOPWBIN)) == NULL)
  1078.     {    fprintf(pgpout,PSTR("\n\007Can't create output file to update key ring.\n"));
  1079.         fclose(f);
  1080.         return(-1);
  1081.     }
  1082.  
  1083.     /* Copy pre-key and key to file g */
  1084.     rewind(f);
  1085.     copyfile (f, g, insertpos);
  1086.  
  1087.     /* write out certificate record to outfile ... */
  1088.     fwrite(certificate,1,certificate_length,g);
  1089.  
  1090.     /* Copy the remainder from file f to file g */
  1091.     copyfile (f, g, -1L);
  1092.     
  1093.     if (write_error(g))
  1094.     {    fclose(g);
  1095.         return(-1);
  1096.     }
  1097.     fclose(g);
  1098.  
  1099.     savetempbak(scratchf,keyfile);
  1100.  
  1101.     fprintf(pgpout, PSTR("\nKey compromise certificate created.\n"));
  1102.     return(0);    /* normal return */
  1103. }    /* compromise */
  1104.  
  1105. /*======================================================================*/
  1106.  
  1107.  
  1108. int signkey(char *keyguffin, char *sigguffin, char *keyfile)
  1109. /*  Write an RSA-signed message digest of key for user keyguffin in
  1110.     keyfile, using signature from user sigguffin.  Append
  1111.     the signature right after the key.
  1112. */
  1113. {    
  1114.     FILE *f;
  1115.     FILE *g;
  1116.     byte ctb;    /* Cipher Type Byte */
  1117.     int certificate_length;    /* signature certificate length */
  1118.     byte certificate[MAX_SIGCERT_LENGTH];
  1119.     byte keyID[KEYFRAGSIZE], keyID2[KEYFRAGSIZE];
  1120.     word32 tstamp; byte *timestamp = (byte *) &tstamp;
  1121.     byte userid[256];
  1122.     unit n[MAX_UNIT_PRECISION], e[MAX_UNIT_PRECISION];
  1123.     char pubring[MAX_PATH];
  1124.     long fp, fpusr;
  1125.     int pktlen, usrpktlen, usrctrllen;
  1126.     char *tempring;
  1127.     int status;
  1128.  
  1129.     /* Get signature key ID */
  1130.     strcpy((char *)userid,sigguffin);    /* Who we are looking for */
  1131.     if (getsecretkey(0, NULL, NULL, timestamp, NULL, NULL,
  1132.                      userid, n, e, NULL, NULL, NULL, NULL) < 0)
  1133.     {
  1134.         return(-1);    /* problem with secret key file. error return. */
  1135.     }
  1136.     extract_keyID(keyID, n);    /* Remember signer key ID */
  1137.     buildfilename(pubring,PUBLIC_KEYRING_FILENAME); /* use default pathname */
  1138.     if ((status = getpublickey(GPK_NORVK, pubring, &fp, &pktlen, keyID,
  1139.             timestamp, userid, n, e)) < 0)
  1140.         return(-1);    /* problem with public key file. error return. */
  1141.  
  1142.     strcpy((char *)userid, keyguffin);
  1143.     fprintf(pgpout, PSTR("\nLooking for key for user '%s':\n"), 
  1144.         LOCAL_CHARSET((char *)userid));
  1145.  
  1146.     if (getpublickey(GPK_SHOW|GPK_NORVK, keyfile, &fp, &pktlen, NULL,
  1147.             timestamp, userid, n, e) < 0)
  1148.         return(-1);
  1149.     PascalToC((char *) userid);
  1150.     if (getpubuserid (keyfile, fp, (byte *)keyguffin, &fpusr, &usrpktlen, FALSE) < 0)
  1151.         return(-1);
  1152.  
  1153.     /* open file f for read, in binary (not text) mode...*/
  1154.     if ((f = fopen(keyfile,FOPRBIN)) == NULL)
  1155.     {    fprintf(pgpout,PSTR("\n\007Can't open key ring file '%s'\n"),keyfile);
  1156.         return(-1);
  1157.     }
  1158.  
  1159.     /* See if there is another signature with this keyID already */
  1160.     fseek (f, fpusr+usrpktlen, SEEK_SET);
  1161.     nextkeypacket(f, &ctb);        /* Add key control packet to len */
  1162.     usrctrllen = 0;
  1163.     if (ctb != CTB_KEYCTRL)
  1164.         fseek(f,fpusr+usrpktlen,SEEK_SET);
  1165.     else
  1166.         usrctrllen = (int) (ftell(f) - (fpusr+usrpktlen));
  1167.     for ( ; ; )
  1168.     {    status = readkeypacket(f,FALSE,&ctb,NULL,NULL,NULL,NULL,
  1169.                     NULL,NULL,NULL,NULL,keyID2,NULL);
  1170.         if (status < 0  ||  is_key_ctb (ctb)  ||  ctb==CTB_USERID)
  1171.             break;
  1172.         if (equal_buffers(keyID, keyID2, KEYFRAGSIZE))
  1173.         {    fprintf(pgpout,PSTR("\n\007Key is already signed by user '%s'.\n"),
  1174.                 LOCAL_CHARSET(sigguffin));
  1175.             fclose(f);
  1176.             return(-1);
  1177.         }
  1178.     }
  1179.     rewind(f);
  1180.  
  1181.     if (!batchmode)
  1182.     {    fprintf(pgpout,
  1183. PSTR("\n\nREAD CAREFULLY:  Based on your own direct first-hand knowledge, are\n\
  1184. you absolutely certain that you are prepared to solemnly certify that\n\
  1185. the above public key actually belongs to the user specified by the\n\
  1186. above user ID (y/N)? "));
  1187.         if (!getyesno('n'))
  1188.         {    fclose(f);
  1189.             return(-1);
  1190.         }
  1191.     }
  1192.  
  1193.     {    /* temporary scope for some buffers */
  1194.         MD5_CTX MD;
  1195.         unit d[MAX_UNIT_PRECISION];
  1196.         unit p[MAX_UNIT_PRECISION], q[MAX_UNIT_PRECISION], u[MAX_UNIT_PRECISION];
  1197.  
  1198.         set_precision(MAX_UNIT_PRECISION);    /* safest opening assumption */
  1199.  
  1200.         if ((g = fopen(keyfile,FOPRBIN)) == NULL)
  1201.         {    fprintf(pgpout,PSTR("\n\007Can't open key ring file '%s'\n"),keyfile);
  1202.             return(-1);
  1203.         }
  1204.         fseek(g, fp, SEEK_SET);
  1205.         /* Calculate signature */
  1206.         if (MDfile0_len(&MD, g, pktlen) < 0)
  1207.         {    fclose(g);
  1208.             fclose(f);
  1209.             return(-1);    /* problem with input file.  error return */
  1210.         }
  1211.         fclose(g);
  1212.  
  1213.         /* Add data from user id */
  1214.         CToPascal((char *)userid);
  1215.         MD5Update(&MD, userid+1, (int)(unsigned char)userid[0]);
  1216.  
  1217.         strcpy((char *)userid,sigguffin);    /* Who we are looking for */
  1218.  
  1219.         /* Make sure that we DONT use the internal password to
  1220.          * get the secret key!  This way you need to type your
  1221.          * pass phrase every time you come to this point!
  1222.          * Derek Atkins        <warlord@MIT.EDU>    93-02-25
  1223.          */
  1224.         if (getsecretkey(GPK_ASKPASS, NULL, NULL, timestamp, NULL, NULL,
  1225.                          userid, n, e, d, p, q, u) < 0)
  1226.         {    fclose(f);
  1227.             return(-1);    /* problem with secret key file. error return. */
  1228.         }
  1229.  
  1230.         certificate_length = make_signature_certificate(certificate, &MD,
  1231.             K0_SIGNATURE_BYTE, e, d, p, q, u, n);
  1232.         if (certificate_length < 0)
  1233.             return(-1);    /* error return from make_signature_certificate() */
  1234.  
  1235.     }    /* end of scope for some buffers */
  1236.  
  1237.     /* open file g for write, in binary (not text) mode...*/
  1238.     tempring = tempfile(TMP_TMPDIR);
  1239.     if ((g = fopen(tempring,FOPWBIN)) == NULL)
  1240.     {    fprintf(pgpout,PSTR("\n\007Can't create output file to update key ring.\n"));
  1241.         fclose(f);
  1242.         return(-1);
  1243.     }
  1244.  
  1245.     /* Copy pre-key and key to file g */
  1246.     copyfile (f, g, fpusr+usrpktlen+usrctrllen);
  1247.  
  1248.     /* write out certificate record to outfile ... */
  1249.     fwrite(certificate,1,certificate_length,g);
  1250.  
  1251.     /* Add "trusty" control packet */
  1252.     write_trust (g, KC_SIGTRUST_ULTIMATE|KC_CONTIG|KC_SIG_CHECKED);
  1253.  
  1254.     /* Copy the remainder from file f to file g */
  1255.     copyfile (f, g, -1L);
  1256.     
  1257.     fclose(f);
  1258.     if (write_error(g))
  1259.     {    fclose(g);
  1260.         return(-1);
  1261.     }
  1262.     fclose(g);
  1263.  
  1264.     savetempbak(tempring,keyfile);
  1265.  
  1266.     fprintf(pgpout, PSTR("\nKey signature certificate added.\n"));
  1267.     return(0);    /* normal return */
  1268.  
  1269. }    /* signkey */
  1270.  
  1271.  
  1272. /*======================================================================*/
  1273.  
  1274. int check_signaturefile(char *infile, char *outfile, boolean strip_signature,
  1275.             char *preserved_name)
  1276. {    /* Check signature in infile for validity.  Strip off the signature
  1277.        and write the remaining packet to outfile.  If strip_signature,
  1278.        also write the signature to outfile.sig.
  1279.        the original filename is stored in preserved_name
  1280.     */
  1281.     byte ctb,ctb2=0;    /* Cipher Type Bytes */
  1282.     char keyfile[MAX_PATH];    /* for getpublickey */
  1283.     char sigfile[MAX_PATH]; /* .sig file if strip_signature */
  1284.     char plainfile[MAX_PATH]; /* buffer for getstring() */
  1285. #ifndef CANONICAL_TEXT
  1286.     char *tempFileName;        /* Name for temporary uncanonicalized file */
  1287.     FILE *tempFile;
  1288. #endif /* !CANONICAL_TEXT */
  1289.     long fp;
  1290.     FILE *f;
  1291.     FILE *g;
  1292.     long start_text;    /* marks file position */
  1293.     int i,count;
  1294.     word16 cert_length;
  1295.     byte certbuf[MAX_SIGCERT_LENGTH];
  1296.     byteptr certificate; /* for parsing certificate buffer */
  1297.     unit n[MAX_UNIT_PRECISION], e[MAX_UNIT_PRECISION];
  1298.     byte inbuf[MAX_BYTE_PRECISION];
  1299.     byte outbuf[MAX_BYTE_PRECISION];
  1300.     byte keyID[KEYFRAGSIZE];
  1301.     word32 tstamp;
  1302.     byte *timestamp = (byte *) &tstamp;        /* key certificate timestamp */
  1303.     word32 dummystamp;
  1304.     byte userid[256];
  1305.     MD5_CTX MD;
  1306.     byte digest[16];
  1307.     boolean separate_signature;
  1308.     boolean fixedLiteral = FALSE;    /* Whether it's a fixed literal2 packet */
  1309.     extern char **myArgv;
  1310.     extern int myArgc;
  1311.     char lit_mode = MODE_BINARY;
  1312.     unsigned char litfile[MAX_PATH];
  1313.     word32 text_len = -1;
  1314.     int    status;
  1315.     byte    *mdextras;
  1316.     byte    mdlensave;
  1317.     byte    version;
  1318.     byte    mdlen;    /* length of material to be added to MD calculation */
  1319.     byte    class;
  1320.     byte    algorithm;
  1321.     byte    mdlow2[2];
  1322.     char    org_sys[5];        /* Name of originating system */
  1323. #ifdef VMS
  1324.     char    *fdl;
  1325.     short    fdl_len;
  1326. #endif
  1327.     int        outbufoffset;
  1328.  
  1329.     fill0( keyID, KEYFRAGSIZE );
  1330.  
  1331.     set_precision(MAX_UNIT_PRECISION);    /* safest opening assumption */
  1332.  
  1333.     buildfilename(keyfile,PUBLIC_KEYRING_FILENAME); /* use default pathname */
  1334.  
  1335.     if (verbose)
  1336.         fprintf(pgpout,"check_signaturefile: infile = '%s', outfile = '%s'\n",
  1337.         infile,outfile);
  1338.  
  1339.     if (preserved_name)
  1340.         *preserved_name = '\0';
  1341.  
  1342.     /* open file f for read, in binary (not text) mode...*/
  1343.     if ((f = fopen(infile,FOPRBIN)) == NULL)
  1344.     {    fprintf(pgpout,PSTR("\n\007Can't open ciphertext file '%s'\n"),infile);
  1345.         return(-1);
  1346.     }
  1347.  
  1348.     /******************** Read header CTB and length field ******************/
  1349.  
  1350.     fread(&ctb,1,1,f);    /* read certificate CTB byte */
  1351.     certificate = certbuf;
  1352.     *certificate++ = ctb;    /* copy ctb into certificate */
  1353.  
  1354.     if (!is_ctb(ctb) || !is_ctb_type(ctb,CTB_SKE_TYPE))
  1355.         goto badcert;    /* complain and return bad status */
  1356.  
  1357.     cert_length = getpastlength(ctb, f); /* read certificate length */
  1358.     certificate += ctb_llength(ctb);    /* either 1, 2, 4, or 8 */
  1359.     if (cert_length > MAX_SIGCERT_LENGTH-3)    /* Huge packet length */
  1360.         goto badcert;    /* complain and return bad status */
  1361.  
  1362.     /* read whole certificate: */
  1363.     if (fread((byteptr) certificate, 1, cert_length, f) < cert_length)
  1364.         /* bad packet length field */
  1365.         goto badcert;    /* complain and return bad status */
  1366.  
  1367.     version = *certificate++;
  1368.     if (version_error(version, VERSION_BYTE))
  1369.         goto err1;
  1370.  
  1371.     mdlensave = mdlen = *certificate++;    /* length of material to be added to MD */
  1372.     mdextras = certificate;    /* pointer to extra material for MD calculation */
  1373.  
  1374.     class = *certificate++;
  1375.     if (class != SM_SIGNATURE_BYTE  &&  class != SB_SIGNATURE_BYTE)
  1376.     {    (void) version_error(class, SM_SIGNATURE_BYTE);
  1377.         goto err1;
  1378.     }
  1379.     mdlen--;
  1380.  
  1381.     if (mdlen>0)    /* if more MD material is included... */
  1382.     {    for (i=0; i<SIZEOF_TIMESTAMP; ++i)
  1383.         {    timestamp[i] = *certificate++;
  1384.             mdlen--;
  1385.         }
  1386.     }
  1387.  
  1388.     if (mdlen>0)    /* if more MD material is included... */
  1389.     {    certificate+=2;    /* skip past unused validity period field */
  1390.         mdlen-=2;
  1391.     }
  1392.  
  1393.     for (i=0; i<KEYFRAGSIZE; i++)
  1394.         keyID[i] = *certificate++; /* copy rest of key fragment */
  1395.  
  1396.     algorithm = *certificate++;
  1397.     if (version_error(algorithm, RSA_ALGORITHM_BYTE))
  1398.         goto err1;
  1399.  
  1400.     algorithm = *certificate++;
  1401.     if (version_error(algorithm, MD5_ALGORITHM_BYTE))
  1402.         goto err1;
  1403.  
  1404.     mdlow2[0] = *certificate++;
  1405.     mdlow2[1] = *certificate++;
  1406.  
  1407.     /* getpublickey() sets precision for mpi2reg, if key not found: use
  1408.        maximum precision to avoid error return from mpi2reg() */
  1409.     if (getpublickey(0, keyfile, &fp, NULL, keyID,
  1410.             (byte *)&dummystamp, userid, n, e) < 0)
  1411.         set_precision(MAX_UNIT_PRECISION);    /* safest opening assumption */
  1412.  
  1413.     if (mpi2reg((unitptr)inbuf,certificate) == -1)    /* get signed message digest */
  1414.         goto err1;
  1415.     certificate += countbytes((unitptr)inbuf)+2;
  1416.  
  1417.     if ((certificate-certbuf) != cert_length+3)
  1418.         /*    Bad length in signature certificate.  Off by 
  1419.             ((certificate-certbuf) - (cert_length+3)) */
  1420.         goto badcert;    /* complain and return bad status */
  1421.  
  1422.     start_text = ftell(f);    /* mark position of text for later */
  1423.  
  1424.     if (fread(outbuf,1,1,f) < 1)    /* see if any plaintext is there */
  1425.     {    /*    Signature certificate has no plaintext following it.
  1426.             Must be in another file.  Go look. */
  1427.         separate_signature = TRUE;
  1428.         if (preserved_name)    /* let caller know there is no output file */
  1429.             strcpy(preserved_name, "/dev/null");
  1430.         fclose(f);
  1431.         fprintf(pgpout,PSTR("\nFile '%s' has signature, but with no text."),infile);
  1432.         if (myArgc > 3 && file_exists(myArgv[3]))
  1433.         {    outfile = myArgv[3];
  1434.             fprintf(pgpout,PSTR("\nText is assumed to be in file '%s'.\n"),outfile);
  1435.         }
  1436.         else
  1437.         {    strcpy(plainfile, outfile);
  1438.             outfile = plainfile;
  1439.             drop_extension(outfile);
  1440.  
  1441.             if (file_exists(outfile))
  1442.                 fprintf(pgpout,PSTR("\nText is assumed to be in file '%s'.\n"),outfile);
  1443.             else
  1444.             {    
  1445.                 if (batchmode)
  1446.                     return -1;
  1447.                 fprintf(pgpout,PSTR("\nPlease enter filename of text that signature applies to: "));
  1448.                 getstring(outfile,59,TRUE);    /* echo keyboard */
  1449.                 if ((int)strlen(outfile) == 0)
  1450.                     return(-1);
  1451.             }
  1452.         }
  1453.         /* open file f for read, in binary (not text) mode...*/
  1454.         if ((f = fopen(outfile,FOPRBIN)) == NULL)
  1455.         {    fprintf(pgpout,PSTR("\n\007Can't open file '%s'\n"),outfile);
  1456.             return(-1);
  1457.         }
  1458.         start_text = ftell(f);    /* mark position of text for later */
  1459.          text_len = fsize(f);    /* remember length of text */
  1460.     }    /* had to open new input file */
  1461.     else
  1462.     {    separate_signature = FALSE;
  1463.         /*    We just read 1 byte, so outbuf[0] should contain a ctb, 
  1464.             maybe a CTB_LITERAL byte. */
  1465.         ctb2 = outbuf[0];
  1466.         fixedLiteral = is_ctb_type(ctb2,CTB_LITERAL2_TYPE);
  1467.         if (is_ctb(ctb2) && (is_ctb_type(ctb2,CTB_LITERAL_TYPE)||fixedLiteral))
  1468.         {    /* Read literal data */
  1469.             text_len = getpastlength(ctb2, f); /* read packet length */
  1470.             lit_mode = '\0';
  1471.             fread (&lit_mode,1,1,f);    /* get literal packet mode byte */
  1472.             if (lit_mode != MODE_TEXT && lit_mode != MODE_BINARY &&
  1473.                 lit_mode != MODE_LOCAL)
  1474.             {    fprintf(pgpout,"\n\007Error: Illegal mode byte %02x in literal packet.\n",
  1475.                     lit_mode);    /* English-only diagnostic for debugging */
  1476.                 (void) version_error(lit_mode, MODE_BINARY);
  1477.                 goto err1;
  1478.             }
  1479.             if (verbose)
  1480.                 fprintf(pgpout, PSTR("File type: '%c'\n"), lit_mode);
  1481.             /* Read literal file name, use it if possible */
  1482.             litfile[0] = 0;
  1483.             fread (litfile,1,1,f);
  1484.             if( fixedLiteral )
  1485.                 /* Get corrected text_len value by subtracting the length of
  1486.                    the filename and the timestamp and mode byte and litfile length byte */
  1487.                 text_len -= litfile[0] + sizeof(dummystamp) + 2;
  1488.             if (litfile[0] > 0)
  1489.             {    if ((int)litfile[0] >= MAX_PATH)
  1490.                 {    fseek(f, litfile[0], SEEK_CUR);
  1491.                     litfile[0] = 0;
  1492.                 }
  1493.                 else
  1494.                     fread (litfile+1,1,litfile[0],f);
  1495.             }
  1496.             /* Use litfile if it's writeable and he didn't say an outfile */
  1497.             if (litfile[0])
  1498.             {    PascalToC( (char *)litfile );
  1499.                 if (verbose)
  1500.                     fprintf(pgpout, PSTR("Original plaintext file name was: '%s'\n"), litfile);
  1501.                 if (preserved_name)
  1502.                     strcpy(preserved_name, (char *) litfile);
  1503.             }
  1504.             if (lit_mode == MODE_LOCAL) {
  1505.                 fread(org_sys, 1, 4, f); org_sys[4] = '\0';
  1506. #ifdef VMS
  1507. #define LOCAL_TEST !strncmp("VMS ",org_sys,4)
  1508. #else
  1509. #define LOCAL_TEST FALSE
  1510. #endif
  1511.                 if (LOCAL_TEST) {
  1512. #ifdef VMS
  1513.                     fread(&fdl_len, 2, 1, f);
  1514.                     fdl = (char *) malloc(fdl_len);
  1515.                     fread(fdl, 1, fdl_len, f);
  1516.                     if ((g = fdl_create( fdl, fdl_len, outfile, (char *) litfile)) == NULL) {
  1517.                         fprintf(pgpout,"\n\007Unable to create file %s\n", outfile);
  1518.                         return(-1);
  1519.                     }
  1520.                     free(fdl);
  1521.                     if (preserved_name)
  1522.                         strcpy(preserved_name, (char *) litfile);
  1523.                     text_len -= (fdl_len + sizeof(fdl_len));
  1524. #endif /* VMS */
  1525.                 } else {
  1526.                     fprintf(pgpout,"\n\007Unrecognised local binary type %s\n",org_sys);
  1527.                     return(-1);
  1528.                 }
  1529.             } else {
  1530.                 /* Discard file creation timestamp for now */
  1531.                 fread (&dummystamp, 1, sizeof(dummystamp), f);
  1532.             }
  1533.             start_text = ftell(f);    /* mark position of text for later */
  1534.         }    /* packet is CTB_LITERAL_TYPE */
  1535.     }
  1536.  
  1537.     /* Use keyID prefix to look up key... */
  1538.  
  1539.     /*    Get and validate public key from a key file: */
  1540.     if (getpublickey(0, keyfile, &fp, NULL, keyID,
  1541.             (byte *)&dummystamp, userid, n, e) < 0)
  1542.     {    /* Can't get public key.  Complain and process file copy anyway. */
  1543.         fprintf(pgpout,PSTR("\n\007WARNING: Can't find the right public key-- can't check signature integrity.\n"));
  1544.         goto outsig;
  1545.     }    /* Can't find public key */
  1546.  
  1547.     count = rsa_public_decrypt(outbuf, (unitptr)inbuf, e, n);
  1548.  
  1549.     if (!quietmode)
  1550.         fputc('.',pgpout);    /* Signal RSA completion. */
  1551.  
  1552.     if (count == -1)
  1553.     {    fprintf(pgpout,PSTR("\n\007Error: RSA-decrypted block is corrupted.\n\
  1554. This may be caused either by corrupted data or by using the wrong RSA key.\n"));
  1555.         goto outsig;    /* Output data anyway */
  1556.     }
  1557.  
  1558.     /* outbuf should contain message digest packet */
  1559.     /*==================================================================*/
  1560.     /* Look at nested stuff within RSA block... */
  1561.  
  1562.     if (count == -2 || count != sizeof(digest))
  1563.     {    fprintf(pgpout,PSTR("\007\nUnrecognized message digest algorithm.\n"));
  1564.         fprintf(pgpout,PSTR("This may require a newer version of PGP.\n"));
  1565.         fprintf(pgpout,PSTR("Can't check signature integrity.\n"));
  1566.         goto outsig;    /* Output data anyway */
  1567.     }
  1568.  
  1569.     /* Distinguish PKCS-compatible from pre-3.3 which has an extra byte */
  1570.     outbufoffset = (count==sizeof(digest)) ? 0 : 1;
  1571.  
  1572.     if (outbuf[outbufoffset] != mdlow2[0]  ||
  1573.         outbuf[outbufoffset+1] != mdlow2[1])
  1574.     {    fprintf(pgpout,PSTR("\n\007Error: RSA-decrypted block is corrupted.\n\
  1575. This may be caused either by corrupted data or by using the wrong RSA key.\n"));
  1576.         goto outsig;    /* Output data anyway */
  1577.     }
  1578.  
  1579.     /* Reposition file to where that plaintext begins... */
  1580.     fseek(f,start_text,SEEK_SET); /* reposition file from last ftell */
  1581.  
  1582.     MDfile0_len(&MD,f,text_len);/* compute a message digest from rest of file */
  1583.  
  1584.     MD_addbuffer (&MD, mdextras, mdlensave, digest); /* Finish message digest */
  1585.  
  1586.     convert_byteorder(timestamp,4); /* convert timestamp from external form */
  1587.     PascalToC((char *)userid);    /* for display */
  1588.  
  1589.     /* now compare computed MD with claimed MD */
  1590. /* Assume MSB external byte ordering */
  1591.     if (!equal_buffers(digest, outbuf+outbufoffset, 16))
  1592.     {
  1593. #ifndef CANONICAL_TEXT
  1594.         /*    IF the signature is bad, AND this machine does not use MSDOS-style
  1595.             canonical text as its native text format, AND this is a detached
  1596.             signature certificate, AND this file appears to contain non-
  1597.             canonical ASCII text, THEN we convert the file to canonical text
  1598.             form and check the signature again.  This is because a detached
  1599.             signature certificate probably means the file is not currently in
  1600.             a canonical text packet, but it was in canonical text form when 
  1601.             the signature was created, so by re-canonicalizing it we can
  1602.             check the signature. */
  1603.         if (class == SM_SIGNATURE_BYTE && separate_signature && is_text_file(outfile))
  1604.         {    /* Reposition file to where the plaintext begins and canonicalize it */
  1605.             rewind( f );
  1606.             tempFileName = tempfile( TMP_WIPE | TMP_TMPDIR );
  1607.             if (verbose)
  1608.                 fprintf(stderr, "signature checking failed, trying in canonical mode\n");
  1609.             if( ( tempFile = fopen( tempFileName, FOPWPBIN ) ) != NULL )
  1610.             {    /* We've opened a temporary work file, copy the text to it
  1611.                    with canonicalization */
  1612.                 copyfile_to_canon( f, tempFile, -1L );
  1613.  
  1614.                 /* Move back to the start of the file and recalculate the MD */
  1615.                 rewind( tempFile );
  1616.                 MDfile0_len( &MD, tempFile, -1L );
  1617.                 MD_addbuffer( &MD, mdextras, mdlensave, digest );
  1618.  
  1619.                 /* Clean up behind us */
  1620.                 fclose( tempFile );
  1621.                 rmtemp( tempFileName );
  1622.  
  1623.                 /* Check if the signature is OK this time round */
  1624. /* Assume MSB external byte ordering */
  1625.                 if(equal_buffers(digest, outbuf+outbufoffset, 16))
  1626.                     goto goodsig;
  1627.             }
  1628.         }
  1629. #endif    /* !CANONICAL_TEXT */
  1630.  
  1631.         fprintf(pgpout,PSTR("\007\nWARNING: Bad signature, doesn't match file contents!\007\n"));
  1632.         fprintf(pgpout,PSTR("\nBad signature from user \"%s\".\n"),
  1633.             LOCAL_CHARSET((char *)userid));
  1634.         fprintf(pgpout,PSTR("Signature made %s\n"),ctdate((word32 *)timestamp));
  1635.         if (moreflag && !batchmode)
  1636.         {    /* more will scroll the message off the screen */
  1637.             fprintf(pgpout, PSTR("\nPress ENTER to continue..."));
  1638.             fflush(pgpout);
  1639.             getyesno('n');
  1640.         }
  1641.         goto warnsig;    /* Output data anyway */
  1642.     }
  1643.  
  1644. goodsig:
  1645.     signature_checked = TRUE;    /* set flag for batch processing */
  1646.     fprintf(pgpout,PSTR("\nGood signature from user \"%s\".\n"),
  1647.         LOCAL_CHARSET((char *)userid));
  1648.     fprintf(pgpout,PSTR("Signature made %s\n"),ctdate((word32 *)timestamp));
  1649.  
  1650. warnsig:
  1651.     /* warn only, don't ask if user wants to use the key */
  1652.     warn_signatures(keyfile, fp, (char *)userid, TRUE);
  1653.  
  1654. outsig:
  1655.     /* Reposition file to where that plaintext begins... */
  1656.     fseek(f,start_text,SEEK_SET); /* reposition file from last ftell */
  1657.  
  1658.     if (separate_signature)
  1659.     {
  1660.         if (!quietmode)
  1661.             fprintf(pgpout,PSTR("\nSignature and text are separate.  No output file produced. "));
  1662.     }
  1663.     else    /* signature precedes plaintext in file... */
  1664.     {    /* produce a plaintext output file from signature file */
  1665.         /* open file g for write, in binary or text mode...*/
  1666.         if (lit_mode==MODE_LOCAL) {
  1667. #ifdef VMS
  1668.             if (status = fdl_copyfile2bin( f, g, text_len)) {   /*  Copy ok? */
  1669.                 if (status > 0)
  1670.                     fprintf(stderr,"\n...copying to literal file\n");
  1671.                 else
  1672.                     perror("\nError copying from work file");
  1673.                 fdl_close(g);
  1674.                 goto err1;
  1675.             }
  1676.             fdl_close(g);
  1677. #endif /*VMS */
  1678.         }
  1679.         else
  1680.         {
  1681.             if (lit_mode == MODE_BINARY)
  1682.                 g = fopen(outfile, FOPWBIN);
  1683.             else
  1684.                 g = fopen(outfile, FOPWTXT);
  1685.             if (g == NULL)
  1686.             {    fprintf(pgpout,PSTR("\n\007Can't create plaintext file '%s'\n"),outfile);
  1687.                 goto err1;
  1688.             }
  1689.             CONVERSION = (lit_mode == MODE_TEXT) ? EXT_CONV : NO_CONV;
  1690.             if (lit_mode == MODE_BINARY)
  1691.                 status = copyfile(f, g, text_len);
  1692.             else
  1693.                 status = copyfile_from_canon(f, g, text_len);
  1694.             CONVERSION = NO_CONV;
  1695.             if (write_error(g) || status < 0)
  1696.             {    fclose(g);
  1697.                 goto err1;
  1698.             }
  1699.             fclose(g);
  1700.         }
  1701.  
  1702.         if (strip_signature)
  1703.         {    /* Copy signature to a .sig file */
  1704.             strcpy (sigfile, outfile);
  1705.             force_extension(sigfile,SIG_EXTENSION);
  1706.             if (!force_flag && file_exists(sigfile))
  1707.             {    fprintf(pgpout,PSTR("\n\007Signature file '%s' already exists.  Overwrite (y/N)? "),
  1708.                     sigfile);
  1709.                 if (!getyesno('n'))
  1710.                     goto err1;
  1711.             }
  1712.             if ((g = fopen(sigfile,FOPWBIN)) == NULL)
  1713.             {    fprintf(pgpout,PSTR("\n\007Can't create signature file '%s'\n"),sigfile);
  1714.                 goto err1;
  1715.             }
  1716.             fseek (f,0L,SEEK_SET);
  1717.             copyfile (f,g,(unsigned long)(cert_length+ctb_llength(ctb)+1));
  1718.             if (write_error(g))
  1719.             {    fclose(g);
  1720.                 goto err1;
  1721.             }
  1722.             fclose(g);
  1723.             if (!quietmode)
  1724.                 fprintf(pgpout,PSTR("\nWriting signature certificate to '%s'\n"),sigfile);
  1725.         }
  1726.     }
  1727.  
  1728.     burn(inbuf);    /* burn sensitive data on stack */
  1729.     burn(outbuf);    /* burn sensitive data on stack */
  1730.     fclose(f);
  1731.     if (separate_signature)
  1732.         return(0);    /* normal return, no nested info */
  1733.     if (is_ctb(ctb2) && (is_ctb_type(ctb2,CTB_LITERAL_TYPE) || fixedLiteral))
  1734.         /* we already stripped away the CTB_LITERAL */
  1735.         return(0);    /* normal return, no nested info */
  1736.     /* Otherwise, it's best to assume a nested CTB */
  1737.     return(1);    /* nested information return */
  1738.  
  1739. badcert:    /* Bad packet.  Complain. */
  1740.     fprintf(pgpout,PSTR("\n\007Error: Badly-formed or corrupted signature certificate.\n"));
  1741.     fprintf(pgpout,PSTR("File \"%s\" does not have a properly-formed signature.\n"),infile);
  1742.     /* Now just drop through to error exit... */
  1743.  
  1744. err1:
  1745.     burn(inbuf);    /* burn sensitive data on stack */
  1746.     burn(outbuf);    /* burn sensitive data on stack */
  1747.     fclose(f);
  1748.     return(-1);    /* error return */
  1749.  
  1750. }    /* check_signaturefile */
  1751.  
  1752.  
  1753. int check_key_sig(FILE *fkey, long fpkey, int keypktlen, char *keyuserid,
  1754.      FILE *fsig, long fpsig, char *keyfile, char *siguserid, byte *xtimestamp,
  1755.      byte *sigclass)
  1756. {    /* Check signature of key in file fkey at position fpkey, using signature
  1757.        in file fsig and position fpsig.  keyfile tells the file to use to
  1758.        look for the public key in to check the sig.  Return 0 if OK, -1 if
  1759.        we can't check the signature, -2 if bad or other problem.
  1760.     */
  1761.     byte ctb;    /* Cipher Type Bytes */
  1762.     long fp;
  1763.     word16 cert_length;
  1764.     int i, count;
  1765.     byte certbuf[MAX_SIGCERT_LENGTH];
  1766.     byteptr certificate; /* for parsing certificate buffer */
  1767.     unit n[MAX_UNIT_PRECISION], e[MAX_UNIT_PRECISION];
  1768.     byte inbuf[MAX_BYTE_PRECISION];
  1769.     byte outbuf[MAX_BYTE_PRECISION];
  1770.     byte keyID[KEYFRAGSIZE];
  1771.     MD5_CTX MD;
  1772.     byte digest[16];
  1773.     byte mdlensave;
  1774.     byte *mdextras;
  1775.     word32 tstamp;
  1776.     byte *timestamp = (byte *) &tstamp;        /* key certificate timestamp */
  1777.     byte    version;
  1778.     byte    mdlen;    /* length of material to be added to MD calculation */
  1779.     byte    class;
  1780.     byte    algorithm;
  1781.     byte    mdlow2[2];
  1782.  
  1783.     fill0( keyID, KEYFRAGSIZE );
  1784.  
  1785.     set_precision(MAX_UNIT_PRECISION);    /* safest opening assumption */
  1786.  
  1787.     /******************** Read header CTB and length field ******************/
  1788.  
  1789.     fseek(fsig, fpsig, SEEK_SET);
  1790.     fread(&ctb,1,1,fsig);    /* read certificate CTB byte */
  1791.     certificate = certbuf;
  1792.     *certificate++ = ctb;    /* copy ctb into certificate */
  1793.  
  1794.     if (!is_ctb(ctb) || !is_ctb_type(ctb,CTB_SKE_TYPE))
  1795.         goto badcert2;    /* complain and return bad status */
  1796.  
  1797.     cert_length = getpastlength(ctb, fsig); /* read certificate length */
  1798.     certificate += ctb_llength(ctb);    /* either 1, 2, 4, or 8 */
  1799.     if (cert_length > MAX_SIGCERT_LENGTH-3)    /* Huge packet length */
  1800.         goto badcert2;    /* complain and return bad status */
  1801.  
  1802.     /* read whole certificate: */
  1803.     if (fread((byteptr) certificate, 1, cert_length, fsig) < cert_length)
  1804.         /* bad packet length field */
  1805.         goto badcert2;    /* complain and return bad status */
  1806.  
  1807.     version = *certificate++;
  1808.     if (version_error(version, VERSION_BYTE))
  1809.         goto err2;
  1810.  
  1811.     mdlensave = mdlen = *certificate++;    /* length of material to be added to MD */
  1812.     mdextras = certificate;    /* pointer to extra material for MD calculation */
  1813.  
  1814.     *sigclass = class = *certificate++;
  1815.     if (class != K0_SIGNATURE_BYTE  &&  class != K1_SIGNATURE_BYTE &&
  1816.         class != K2_SIGNATURE_BYTE  &&  class != K3_SIGNATURE_BYTE &&
  1817.         class != KC_SIGNATURE_BYTE)
  1818.     {    (void) version_error(class, K0_SIGNATURE_BYTE);
  1819.         goto err2;
  1820.     }
  1821.     mdlen--;
  1822.  
  1823.     if (mdlen>0)    /* if more MD material is included... */
  1824.     {    for (i=0; i<SIZEOF_TIMESTAMP; ++i)
  1825.         {    timestamp[i] = *certificate++;
  1826.             mdlen--;
  1827.         }
  1828.     }
  1829.  
  1830.     if (mdlen>0)    /* if more MD material is included... */
  1831.     {    certificate+=2;    /* skip past unused validity period word */
  1832.         mdlen-=2;
  1833.     }
  1834.  
  1835.     if (mdlen>0)    /* if more MD material is included... */
  1836.         certificate+=mdlen;    /* skip over the rest */
  1837.  
  1838.     for (i=0; i<KEYFRAGSIZE; i++)
  1839.         keyID[i] = *certificate++; /* copy rest of key fragment */
  1840.  
  1841.     algorithm = *certificate++;
  1842.     if (version_error(algorithm, RSA_ALGORITHM_BYTE))
  1843.         goto err2;
  1844.  
  1845.     algorithm = *certificate++;
  1846.     if (version_error(algorithm, MD5_ALGORITHM_BYTE))
  1847.         goto err2;
  1848.  
  1849.     /* Grab 1st 2 bytes of message digest */
  1850.     mdlow2[0] = *certificate++;
  1851.     mdlow2[1] = *certificate++;
  1852.  
  1853.     /* We used to set precision here based on certificate value,
  1854.      * but it was sometimes less than that based on n.  Read public
  1855.      * key here to set precision, before we go on.
  1856.      */
  1857.     /* This sets precision, too, based on n. */
  1858.     if (getpublickey(GPK_GIVEUP, keyfile, &fp, NULL, keyID,
  1859.             xtimestamp, (unsigned char *)siguserid, n, e) < 0)
  1860.         goto err1;
  1861.  
  1862.     if (mpi2reg((unitptr)inbuf,certificate) == -1)    /* get signed message digest */
  1863.         goto err1;
  1864.     certificate += countbytes((unitptr)inbuf)+2;
  1865.  
  1866.     if ((certificate-certbuf) != cert_length+3)
  1867.         /*    Bad length in signature certificate.  Off by 
  1868.             ((certificate-certbuf) - (cert_length+3)) */
  1869.         goto badcert2;    /* complain and return bad status */
  1870.  
  1871.     count = rsa_public_decrypt(outbuf, (unitptr)inbuf, e, n);
  1872.  
  1873.     if (count == -2)
  1874.         goto err1;    /* Unrecognized digest algorithm */
  1875.  
  1876.     if (count != sizeof(digest))
  1877.         goto err2;    /* Bad RSA decrypt.  Corruption, or wrong key. */
  1878.  
  1879.     /* outbuf should contain message digest packet */
  1880.     /*==================================================================*/
  1881.     /* Look at nested stuff within RSA block... */
  1882.  
  1883. /* Assume MSB external byte ordering */
  1884.     if (outbuf[0] != mdlow2[0]  || outbuf[1] != mdlow2[1])
  1885.         goto err2;    /* Bad RSA decrypt.  Corruption, or wrong key. */
  1886.  
  1887.     /* Position file to where that plaintext begins... */
  1888.     fseek(fkey,fpkey,SEEK_SET);
  1889.  
  1890.     /* compute a message digest from key packet */
  1891.     MDfile0_len(&MD,fkey,keypktlen);
  1892.     /* Add data from user id */
  1893.     if (class != KC_SIGNATURE_BYTE)
  1894.         MD5Update(&MD, (unsigned char *) keyuserid+1, (int)(unsigned char)keyuserid[0]);
  1895.     /* Add time and class data */
  1896.     MD_addbuffer (&MD, mdextras, mdlensave, digest);    /* Finish message digest */
  1897.  
  1898.     /* now compare computed MD with claimed MD */
  1899. /* Assume MSB external byte ordering */
  1900.     if (!equal_buffers(digest, outbuf, 16))
  1901.         goto err2;
  1902.  
  1903.     convert_byteorder(timestamp,4); /* convert timestamp from external form */
  1904.     memcpy (xtimestamp, timestamp, 4);    /* Return signature timestamp */
  1905.  
  1906.     burn(inbuf);    /* burn sensitive data on stack */
  1907.     burn(outbuf);    /* burn sensitive data on stack */
  1908.     return(0);    /* normal return */
  1909.  
  1910. err1:
  1911.     burn(inbuf);    /* burn sensitive data on stack */
  1912.     burn(outbuf);    /* burn sensitive data on stack */
  1913.     return(-1);    /* error return */
  1914.  
  1915. badcert2:    /* Bad packet.  Complain. */
  1916.     fprintf(pgpout,PSTR("\n\007Error: Badly-formed or corrupted signature certificate.\n"));
  1917.     /* Now just drop through to error exit... */
  1918.  
  1919. err2:
  1920.     burn(inbuf);    /* burn sensitive data on stack */
  1921.     burn(outbuf);    /* burn sensitive data on stack */
  1922.     return(-2);    /* error return */
  1923.  
  1924. }    /* check_key_sig */
  1925.  
  1926.  
  1927.  
  1928. /*======================================================================*/
  1929. static int squish_and_idea_file(byte *ideakey, FILE *f, FILE *g, 
  1930.     boolean attempt_compression)
  1931. {
  1932.     FILE *t;
  1933.     char *tempf = NULL;
  1934.     byte ctb;
  1935.     word32 fpos, fpos0;
  1936.     extern char plainfile[];
  1937.  
  1938.     /*
  1939.     **  If the caller specified that we should attempt compression, we
  1940.     **  create a temporary file 't' and compress our input file 'f' into
  1941.     **  't'.  Ideally, we would see if we get a good compression ratio 
  1942.     **  and if we did, then use file 't' for input and write a 
  1943.     **  CTB_COMPRESSED prefix.  But in this implementation we just always
  1944.     **  use the compressed output, even if it didn't compress well.
  1945.     */
  1946.  
  1947.     rewind( f );
  1948.  
  1949.     if (!attempt_compression)
  1950.         t = f;    /* skip compression attempt */
  1951.     else    /* attempt compression-- get a tempfile */ 
  1952.         if ((tempf = tempfile(TMP_TMPDIR|TMP_WIPE)) == NULL ||
  1953.             (t = fopen(tempf, FOPWPBIN)) == NULL) /* error: no tempfile */
  1954.             t = f;    /* skip compression attempt */
  1955.         else    /* attempt compression */ 
  1956.         {
  1957.             extern int zipup( FILE *, FILE * );
  1958.  
  1959.  
  1960.             if (verbose) fprintf(pgpout,"\nCompressing [%s] ", plainfile);
  1961.  
  1962.             /* We don't put a length field on CTB_COMPRESSED yet */
  1963.             ctb = CTB_COMPRESSED;        /* use compression prefix CTB */
  1964.             fwrite( &ctb, 1, 1, t );    /* write CTB_COMPRESSED */
  1965.               /* No CTB packet length specified means indefinite length. */
  1966.             ctb = ZIP2_ALGORITHM_BYTE;     /* use ZIP compression */
  1967.             fwrite( &ctb, 1, 1, t );    /* write ZIP algorithm byte */
  1968.  
  1969.             /* Compression the file */
  1970.             zipup( f, t);
  1971.             if (write_error(t))
  1972.             {    fclose(t);
  1973.                 if (tempf)
  1974.                     rmtemp(tempf);
  1975.                 return(-1);
  1976.             }
  1977.             if (verbose) fprintf(pgpout, PSTR("compressed.  ") );
  1978.             else if (!quietmode)
  1979.                 fputc('.',pgpout);    /* show progress */
  1980.             rewind( t );
  1981.           }
  1982.  
  1983.     /*    Now write out file thru IDEA cipher... */
  1984.  
  1985.     /* Write CTB prefix, leave 4 bytes for later length */
  1986.     fpos0 = ftell(g);
  1987.     write_ctb_len (g, CTB_CKE_TYPE, 0L, TRUE);
  1988.     fpos = ftell(g) - fpos0;
  1989.  
  1990.     idea_file( ideakey, ENCRYPT_IT, t, g, fsize(t) );
  1991.  
  1992.     /* Now re-write CTB prefix, this time with length */
  1993.     fseek(g,fpos0,SEEK_SET);
  1994.     write_ctb_len (g, CTB_CKE_TYPE, fsize(g)-fpos, TRUE);
  1995.  
  1996.     if (t != f)    
  1997.     {    fclose( t );  /* close and remove the temporary file */
  1998.         if (tempf)
  1999.             rmtemp(tempf);
  2000.     }
  2001.  
  2002.     return(0);    /* normal return */
  2003.  
  2004. }    /* squish_and_idea_file */
  2005.  
  2006.  
  2007. int squish_file(char *infile, char *outfile)
  2008. {
  2009.     FILE *f, *g;
  2010.     byte ctb;
  2011.     extern int zip( FILE *, FILE * );
  2012.  
  2013.     if (verbose)
  2014.         fprintf(pgpout,"squish_file: infile = '%s', outfile = '%s'\n",
  2015.         infile,outfile);
  2016.  
  2017.     /* open file f for read, in binary (not text) mode...*/
  2018.     if ((f = fopen( infile, FOPRBIN )) == NULL)
  2019.     {
  2020.         fprintf(pgpout,PSTR("\n\007Can't open file '%s'\n"), infile );
  2021.         return(-1);
  2022.     }
  2023.  
  2024.     /* open file g for write, in binary (not text) mode...*/
  2025.     if ((g = fopen( outfile, FOPWBIN )) == NULL)
  2026.     {
  2027.         fprintf(pgpout,PSTR("\n\007Can't create compressed file '%s'\n"), outfile );
  2028.         fclose(f);
  2029.         return(-1);
  2030.     }
  2031.  
  2032.  
  2033.     if (verbose) fprintf(pgpout, PSTR("Compressing file..."));
  2034.  
  2035.     /* We don't put a length field on CTB_COMPRESSED yet */
  2036.     ctb = CTB_COMPRESSED;        /* use compression prefix CTB */
  2037.     fwrite( &ctb, 1, 1, g );    /* write CTB_COMPRESSED */
  2038.     /* No CTB packet length specified means indefinite length. */
  2039.     ctb = ZIP2_ALGORITHM_BYTE;     /* use ZIP compression */
  2040.     fwrite( &ctb, 1, 1, g );    /* write ZIP algorithm byte */
  2041.  
  2042.     /* Compress/store the file */
  2043.     zipup( f, g );
  2044.     if (verbose) fprintf(pgpout, PSTR("compressed.  ") );
  2045.  
  2046.     fclose (f);
  2047.     if (write_error(g))
  2048.     {    fclose(g);
  2049.         return -1;
  2050.     }
  2051.     fclose (g);
  2052.     return(0);
  2053. }   /* squish_file */
  2054.  
  2055. #define NOECHO1 1    /* Disable password from being displayed on screen */
  2056. #define NOECHO2 2    /* Disable password from being displayed on screen */
  2057.  
  2058. int idea_encryptfile(char *infile, char *outfile, 
  2059.     boolean attempt_compression)
  2060. {
  2061.     FILE *f;    /* input file */
  2062.     FILE *g;    /* output file */
  2063.     byte ideakey[16];
  2064.     struct hashedpw *hpw;
  2065.  
  2066.     if (verbose)
  2067.         fprintf(pgpout,"idea_encryptfile: infile = '%s', outfile = '%s'\n",
  2068.         infile,outfile);
  2069.  
  2070.     /* open file f for read, in binary (not text) mode...*/
  2071.     if ((f = fopen( infile, FOPRBIN )) == NULL)
  2072.     {
  2073.         fprintf(pgpout,PSTR("\n\007Can't open plaintext file '%s'\n"), infile );
  2074.         return(-1);
  2075.     }
  2076.  
  2077.     /* open file g for write, in binary (not text) mode...*/
  2078.     if ((g = fopen( outfile, FOPWBIN )) == NULL)
  2079.     {
  2080.         fprintf(pgpout,PSTR("\n\007Can't create ciphertext file '%s'\n"), outfile );
  2081.         fclose(f);
  2082.         return(-1);
  2083.     }
  2084.  
  2085.     /* Get IDEA password, hashed to a key */
  2086.     if (passwds)
  2087.     {    memcpy(ideakey, passwds->hash, sizeof(ideakey));
  2088.         memset(passwds->hash, 0, sizeof(passwds->hash));
  2089.         hpw = passwds;
  2090.         passwds = passwds->next;
  2091.         free(hpw);
  2092.     }
  2093.     else
  2094.     {    if (!quietmode)
  2095.             fprintf(pgpout,PSTR("\nYou need a pass phrase to encrypt the file. "));
  2096.         if (batchmode || GetHashedPassPhrase((char *)ideakey,NOECHO2) <= 0)
  2097.         {    fclose(f);
  2098.             fclose(g);
  2099.             return(-1);
  2100.         }
  2101.     }
  2102.  
  2103.     if (!quietmode)
  2104.     {    fprintf(pgpout,PSTR("Just a moment..."));  /* this may take a while */
  2105.         fflush(pgpout);
  2106.     }
  2107.  
  2108.     /* Now compress the plaintext and encrypt it with IDEA... */
  2109.     squish_and_idea_file( ideakey, f, g, attempt_compression );
  2110.  
  2111.     burn(ideakey);    /* burn sensitive data on stack */
  2112.  
  2113.     fclose(f);
  2114.     if (write_error(g))
  2115.     {    fclose(g);
  2116.         return -1;
  2117.     }
  2118.     fclose(g);
  2119.  
  2120.     return(0);
  2121.  
  2122. }    /* idea_encryptfile */
  2123.  
  2124.  
  2125. /*======================================================================*/
  2126.  
  2127. static byte (*keyID_list)[KEYFRAGSIZE] = NULL;
  2128.  
  2129. int encryptfile(char **mcguffins, char *infile, char *outfile, 
  2130.     boolean attempt_compression)
  2131. {
  2132.     int i,ckp_length;
  2133.     FILE *f;
  2134.     FILE *g;
  2135.     byte keybuf[MAX_BYTE_PRECISION]; /* This keeps our IDEA to encrypt */
  2136.     byte ideakey[24]; /* must be big enough for make_random_ideakey */
  2137.     word32 chksum;
  2138.     char keyfile[MAX_PATH];
  2139.     int keys_used = 0;
  2140.  
  2141.     if (mcguffins == NULL || *mcguffins == NULL || **mcguffins == '\0') {
  2142.         /* Well, we haven't gotten a user, lets die here */
  2143.         return -1;    
  2144.     }
  2145.  
  2146.     if (verbose)
  2147.         fprintf(pgpout,"encryptfile: infile = %s, outfile = %s\n",
  2148.         infile,outfile);
  2149.  
  2150.     /* open file f for read, in binary (not text) mode...*/
  2151.     if ((f = fopen( infile, FOPRBIN )) == NULL)
  2152.     {
  2153.         fprintf(pgpout,PSTR("\n\007Can't open plaintext file '%s'\n"), infile );
  2154.         return(-1);
  2155.     }
  2156.  
  2157.     /* open file g for write, in binary (not text) mode...*/
  2158.     if ((g = fopen( outfile, FOPWBIN )) == NULL)
  2159.     {
  2160.         fprintf(pgpout,PSTR("\n\007Can't create ciphertext file '%s'\n"), outfile );
  2161.         fclose(f);
  2162.         return(-1);
  2163.     }
  2164.  
  2165.     /*    Now we have to generate a random session key and IV.
  2166.         As part of this computation, we use the MD5 hash of the
  2167.         current file, if it has previously been obtained due to a
  2168.         signing operation.  If it has not been obtained, we hash
  2169.         the first 2K (for efficiency reasons) for input into
  2170.         the key generatrion process.  This is to ensure that
  2171.         capturing a randseed.bin file will not allow reconstruction
  2172.         of subsequent session keys without knowing the message
  2173.         that was encrypted.  (A session key only protects a
  2174.         single message, so it is reasonable to assume that an
  2175.         opponent trying to obtain a session key is trying to
  2176.         obtain, and thus is ignorant of, the message it encrypts.)
  2177.  
  2178.         This is not perfect, but it's an improvement on how session
  2179.         keys used to be generated, and can be changed in future
  2180.         without compatibility worries.
  2181.     */
  2182.  
  2183.     if (!already_have_md5)    /* Obtain some random bits from the input file */
  2184.     {    MD5_CTX MD;
  2185.  
  2186.         MD5Init(&MD);
  2187.         MDfile0_len(&MD, f, 4096);    /* Ignore errors - what could be done? */
  2188.         MD5Final(md5buf, &MD);
  2189.         already_have_md5 = 1;
  2190.  
  2191.         fseek(f, 0, SEEK_SET); /* Get back to the beginning for encryption */
  2192.     }
  2193.  
  2194.     ckp_length = make_random_ideakey(ideakey);
  2195.     /* Returns a 24 byte random IDEA key */
  2196.  
  2197. /* Assume MSB external byte ordering */
  2198.     /* Prepend identifier byte to key */
  2199.     keybuf[0] = IDEA_ALGORITHM_BYTE;
  2200.     for (i=0; i<ckp_length; ++i)
  2201.         keybuf[i+1] = ideakey[i];
  2202.     /* Compute and append checksum to the key */
  2203.     chksum = checksum (keybuf+1, ckp_length);
  2204.     ckp_length++;
  2205.     put_word16((word16) chksum, keybuf+ckp_length);
  2206.     ckp_length += 2;
  2207.  
  2208.     /* Ok, we now have our IDEA key which we are going to use
  2209.      * to encrypt our packet.  We have stuffed it into a packet
  2210.      * which we can now encrypt in the Public Key of EACH USER
  2211.      * which we want to be able to decrypt this message.  Now we
  2212.      * will walk down mcguffins until we hit a NULL or NULL string,
  2213.      * and we will encrypt for each user in the list, and write
  2214.      * that out to the output file.
  2215.      *
  2216.      * -derek    <warlord@MIT.EDU>    13 Dec 1992
  2217.      */
  2218.  
  2219.     for (i = 0; mcguffins[i] != NULL; ++i)
  2220.         ;
  2221.     if (encrypt_to_self)
  2222.         ++i;
  2223.     keyID_list = xmalloc(i * KEYFRAGSIZE);
  2224.     /* Iterate through users */
  2225.     for (; *mcguffins && **mcguffins ; ++mcguffins) {
  2226.         buildfilename(keyfile,PUBLIC_KEYRING_FILENAME);
  2227.         /* use default pathname */
  2228.  
  2229.         keys_used = 
  2230.             encryptkeyintofile(g, *mcguffins, keybuf,
  2231.                        keyfile, ckp_length, keys_used);
  2232.     } /* for */
  2233.  
  2234.     if (!keys_used)
  2235.     {    fclose(f);
  2236.         fclose(g);
  2237.         free(keyID_list);
  2238.         return -1;
  2239.     }
  2240.  
  2241.     /* encrypt to myself if need be */
  2242.     if (encrypt_to_self && *my_name) {
  2243.         keys_used = 
  2244.             encryptkeyintofile(g, my_name, keybuf,
  2245.                        keyfile, ckp_length, keys_used);
  2246.     }
  2247.     free(keyID_list);
  2248.  
  2249.     close_idearand();
  2250.     /**    Finished with RSA block containing IDEA key. */
  2251.  
  2252.     /* Now compress the plaintext and encrypt it with IDEA... */
  2253.     squish_and_idea_file( ideakey, f, g, attempt_compression );
  2254.  
  2255.     burn(keybuf);    /* burn the Idea Key Packet */
  2256.     burn(ideakey);    /* burn sensitive data on stack */
  2257.  
  2258.     fclose(f);
  2259.     if (write_error(g))
  2260.     {    fclose(g);
  2261.         return -1;
  2262.     }
  2263.     fclose(g);
  2264.  
  2265.     return(0);
  2266. }    /* encryptfile */
  2267.  
  2268.  
  2269. static int
  2270. encryptkeyintofile(FILE *g, char *mcguffin, byte *keybuf,
  2271.            char *keyfile, int ckp_length, int keys_used) {
  2272.     int i;
  2273.     unit n[MAX_UNIT_PRECISION], e[MAX_UNIT_PRECISION];
  2274.     byte keyID[KEYFRAGSIZE];
  2275.     byte inbuf[MAX_BYTE_PRECISION];
  2276.     byte outbuf[MAX_BYTE_PRECISION];
  2277.     word32 tstamp; byte *timestamp = (byte *) &tstamp;        /* key certificate timestamp */
  2278.     byte userid[256];
  2279.     long fp;
  2280.     int blocksize;
  2281.     byte    ver, alg;
  2282.     byte (*keyp)[KEYFRAGSIZE];
  2283.     
  2284.  
  2285.     /* This "loop" is so we can break out at opportune moments */
  2286.     do {
  2287.         userid[0] = '\0';
  2288.         
  2289.         strcpy((char *)userid,mcguffin);
  2290.         /* Who we are looking for (C string) */
  2291.         
  2292.         /* Get and validate public key from a key file: 
  2293.         * We will be nice and ask the user ONCE (and ONLY once)
  2294.         * for a keyfile if its not in the default. 
  2295.         */
  2296.         
  2297.         if (getpublickey((quietmode?0:GPK_SHOW)|GPK_NORVK, keyfile, &fp, NULL, NULL,
  2298.                 timestamp, userid, n, e) < 0)
  2299.         {    fprintf(pgpout, PSTR("\n\007Cannot find the public key matching userid '%s'\n\
  2300. This user will not be able to decrypt this message.\n"), 
  2301.             LOCAL_CHARSET(mcguffin));
  2302.             continue;
  2303.         }
  2304.         
  2305.         /* Make sure we haven't already used this key */
  2306.         extract_keyID(keyID, n);
  2307.         for (keyp = keyID_list; keyp < keyID_list+keys_used; ++keyp)
  2308.         {    if (!memcmp(keyp, keyID, KEYFRAGSIZE)) 
  2309.                 break;
  2310.         }
  2311.  
  2312.         if (keyp < keyID_list + keys_used)
  2313.         {    /* This key was already specified.  Quietly ignore it. */
  2314.             continue;
  2315.         }
  2316.         
  2317.         /* Add this keyID to the list of keys used so far */
  2318.         memcpy(keyp, keyID, KEYFRAGSIZE);
  2319.         
  2320.         PascalToC((char *)userid);
  2321.         if (warn_signatures(keyfile, fp, (char *)userid, 
  2322.                     FALSE) < 0) {
  2323.             fprintf(pgpout, "Ok, skipping userid %s\n", mcguffin);
  2324.             continue;
  2325.         }
  2326.         
  2327.         /* set_precision has been properly called by getpublickey */
  2328.         
  2329.         /*    Note that RSA key must be at least big enough
  2330.             to encipher a complete conventional key packet 
  2331.             in a single RSA block.
  2332.         */
  2333.         
  2334.         blocksize = countbytes(n)-1;    
  2335.         /* size of a plaintext block */
  2336.         
  2337.         if (blocksize < 31) {
  2338.             fprintf(pgpout,"\n\007Error: RSA key length must be at least 256 bits.\n");
  2339.             fprintf(pgpout, "Skipping userid %s\n", mcguffin);
  2340.             continue;
  2341.         }
  2342.         
  2343. #ifdef MR_DEBUG
  2344.         /* XXX This is dangerous... This will print out the
  2345.          * IDEA Key, which is a breach of security!
  2346.          */
  2347.         fprintf(pgpout, "Idea Key: ");
  2348.         for (i = 0; i < ckp_length; i++)
  2349.             fprintf(pgpout, "%02X ", keybuf[i]);
  2350.         fprintf(pgpout, "\n");
  2351. #endif
  2352.         rsa_public_encrypt((unitptr)outbuf, keybuf, ckp_length, e, n);
  2353.         
  2354.         /* write out header record to outfile ... */
  2355.         
  2356.         /* PKE is Public Key Encryption */
  2357.         write_ctb_len (g, CTB_PKE_TYPE,
  2358.                    1+KEYFRAGSIZE+1+2+countbytes((unitptr)outbuf), 
  2359.                    FALSE);
  2360.         
  2361.         /* Write version byte */
  2362.         ver = VERSION_BYTE;
  2363.         fwrite (&ver, 1, 1, g);
  2364.         
  2365.         writekeyID( n, g );    
  2366.         /* write msg prefix fragment of modulus n */
  2367.         
  2368.         /* Write algorithm byte */
  2369.         alg = RSA_ALGORITHM_BYTE;
  2370.         fwrite (&alg, 1, 1, g);
  2371.         
  2372.         /* convert RSA ciphertext block via reg2mpi and 
  2373.         * write to file
  2374.         */
  2375.         
  2376.         write_mpi( (unitptr)outbuf, g, FALSE );
  2377.         
  2378.         burn(inbuf);    /* burn sensitive data on stack */
  2379.         burn(outbuf);    /* burn sensitive data on stack */
  2380.         ++keys_used;
  2381.  
  2382.     } while (0);
  2383.  
  2384.     return(keys_used);
  2385. }        /* encryptkeyintofile */
  2386.  
  2387. /*======================================================================*/
  2388. int make_literal(char *infile, char *outfile, char lit_mode, char *literalfile)
  2389. {    /*    Prepend a CTB_LITERAL prefix to a file.  Convert to canonical form if
  2390.         lit_mode is MODE_TEXT.
  2391.     */
  2392.     char lfile[MAX_PATH];
  2393.     FILE *f;
  2394.     FILE *g;
  2395.     int status = 0;
  2396. #ifdef VMS
  2397.     char *fdl;
  2398.     short fdl_len;
  2399. #endif /* VMS */
  2400.  
  2401.     word32 flen, fpos;
  2402.     word32 dummystamp = 0;
  2403.  
  2404.     if (verbose)
  2405.         fprintf(pgpout,"make_literal: infile = %s, outfile = %s, mode = '%c', literalfile = '%s'\n",
  2406.         infile,outfile,lit_mode,literalfile);
  2407.  
  2408.     /* open file f for read, in binary or text mode...*/
  2409.  
  2410. #ifdef VMS
  2411.     if (lit_mode == MODE_LOCAL) {
  2412.         if (!(fdl_generate(infile, &fdl, &fdl_len ) & 01)) {
  2413.         fprintf(pgpout,PSTR("\n\007Can't open input plaintext file '%s'\n"),infile);
  2414.         return(-1);
  2415.         }
  2416.     }
  2417. #endif /*VMS*/
  2418.     if (lit_mode == MODE_TEXT)
  2419.         f = fopen(infile, FOPRTXT);
  2420.     else
  2421.         f = fopen(infile, FOPRBIN);
  2422.     if (f == NULL)
  2423.     {    fprintf(pgpout,PSTR("\n\007Can't open input plaintext file '%s'\n"),infile);
  2424.         return(-1);
  2425.     }
  2426.     flen = fsize(f);
  2427.  
  2428.     /*     open file g for write, in binary (not text) mode... */
  2429.     if ((g = fopen( outfile,FOPWBIN )) == NULL)
  2430.     {    fprintf(pgpout, PSTR("\n\007Can't create plaintext file '%s'\n"), outfile );
  2431.         goto err1;
  2432.     }
  2433.  
  2434.     if (literalfile == NULL)
  2435.     {    /* Put in a zero byte to indicate no filename */
  2436.         lfile[0] = '\0';
  2437.     }
  2438.     else
  2439.     {    strcpy( lfile, literalfile );
  2440.         file_to_canon( lfile );
  2441.         CToPascal( lfile );
  2442.     }
  2443.  
  2444. #ifdef USE_LITERAL2
  2445. #define    LENGTH_FIELD        (flen + (unsigned char) lfile[0] + 6)
  2446. #define    LIT_TYPE    CTB_LITERAL2_TYPE
  2447. #else
  2448. #define    LENGTH_FIELD    flen
  2449. #define    LIT_TYPE    CTB_LITERAL_TYPE
  2450. #endif
  2451.     if (lit_mode == MODE_BINARY)
  2452.         write_ctb_len (g, LIT_TYPE, LENGTH_FIELD, FALSE);
  2453. #ifdef VMS
  2454.     else if (lit_mode == MODE_LOCAL)
  2455.         write_ctb_len (g, CTB_LITERAL2_TYPE, flen + fdl_len + sizeof(fdl_len) + 6, TRUE);
  2456. #endif /* VMS */
  2457.     else /* Will put in size field later for text mode */
  2458.         write_ctb_len (g, LIT_TYPE, 0L, TRUE);
  2459. #ifdef USE_LITERAL2
  2460.     fpos = ftell(g);
  2461. #endif
  2462.     fwrite ( &lit_mode, 1, 1, g );    /*    write lit_mode */
  2463.  
  2464.     if (lit_mode == MODE_LOCAL) {
  2465. #ifdef VMS
  2466.         write_litlocal( g, fdl, fdl_len);
  2467.         free(fdl);
  2468. #else
  2469.         ;   /*  Null statement if we don't have anything to do! */
  2470. #endif /* VMS */
  2471.     } else {
  2472.         /* write literalfile name */
  2473.         fwrite (lfile, 1, (unsigned char) lfile[0]+1, g);
  2474.         /* Dummy file creation timestamp */
  2475.         fwrite ( &dummystamp, 1, sizeof(dummystamp), g);
  2476.     }
  2477. #ifndef USE_LITERAL2
  2478.     fpos = ftell(g);
  2479. #endif
  2480.  
  2481.     if ((lit_mode == MODE_BINARY) || (lit_mode == MODE_LOCAL)) {
  2482.         if (copyfile( f, g, -1L )) {
  2483.             fprintf(pgpout,"\n\007Unable to append to literal plaintext file");
  2484.             perror("\n");
  2485.             fclose(g);
  2486.             goto err1;
  2487.         }
  2488.     } else {
  2489.         CONVERSION = (lit_mode == MODE_TEXT) ? INT_CONV : NO_CONV;
  2490.         status = copyfile_to_canon( f, g, -1L );
  2491.         CONVERSION = NO_CONV;
  2492.         /* Re-write CTB with correct length info */
  2493.         rewind (g);
  2494.         write_ctb_len (g, LIT_TYPE, fsize(g)-fpos, TRUE);
  2495.     }
  2496.     if (write_error(g) || status < 0)
  2497.     {    fclose(g);
  2498.         goto err1;
  2499.     }
  2500.     fclose(g);
  2501.     fclose(f);
  2502.     return(0);    /* normal return */
  2503.  
  2504. err1:
  2505.     fclose(f);
  2506.     return(-1);    /* error return */
  2507.  
  2508. }    /* make_literal */
  2509. #undef LENGTH_FIELD
  2510. #undef LIT_TYPE
  2511.  
  2512.  
  2513. /*======================================================================*/
  2514. int strip_literal(char *infile, char *outfile, char *preserved_name,
  2515.         char *lit_mode)
  2516. {    /*    Strip off literal prefix from infile, copying to outfile.
  2517.         Get lit_mode and literalfile info from
  2518.         the prefix.  Replace outfile with literalfile unless
  2519.         literalfile is illegal
  2520.         the original filename is stored in preserved_name
  2521.         If lit_mode is MODE_TEXT, convert from canonical form as we
  2522.         copy the data.
  2523.     */
  2524.     byte ctb;    /* Cipher Type Byte */
  2525.     FILE *f;
  2526.     FILE *g;
  2527.     word32 LITlength = 0;
  2528.     unsigned char litfile[MAX_PATH];
  2529.     word32 dummystamp;
  2530.     char    org_sys[5];        /* Name of originating system */
  2531.     int    status;
  2532. #ifdef VMS
  2533.     char    *fdl;
  2534.     short    fdl_len;
  2535. #endif
  2536.     *lit_mode = MODE_BINARY;
  2537.     if (verbose)
  2538.         fprintf(pgpout,"strip_literal: infile = %s, outfile = %s\n",
  2539.         infile,outfile);
  2540.  
  2541.     if (preserved_name)
  2542.         *preserved_name = '\0';
  2543.  
  2544.     /* open file f for read, in binary (not text) mode...*/
  2545.     if ((f = fopen(infile,FOPRBIN)) == NULL)
  2546.     {    fprintf(pgpout,PSTR("\n\007Can't open input plaintext file '%s'\n"),infile);
  2547.         return(-1);
  2548.     }
  2549.  
  2550.     fread(&ctb,1,1,f);    /* read Cipher Type Byte */
  2551.  
  2552.     if (!is_ctb(ctb) || !(is_ctb_type(ctb,CTB_LITERAL_TYPE) ||
  2553.         is_ctb_type(ctb,CTB_LITERAL2_TYPE)))
  2554.     {    /* debug message in English only -- something got corrupted */
  2555.         fprintf(pgpout,"\n\007'%s' is not a literal plaintext file.\n",infile);
  2556.         fclose(f);
  2557.         return(-1);
  2558.     }
  2559.  
  2560.     LITlength = getpastlength(ctb, f); /* read packet length */
  2561.  
  2562.     /* Read literal data */
  2563.     *lit_mode = '\0';
  2564.     fread (lit_mode,1,1,f);
  2565.     if ((*lit_mode != MODE_BINARY) && (*lit_mode != MODE_TEXT)
  2566.         && (*lit_mode != MODE_LOCAL))
  2567.     {    (void) version_error(*lit_mode, MODE_TEXT);
  2568.         fclose(f);
  2569.         return(-1);
  2570.     }
  2571.     if (verbose)
  2572.         fprintf(pgpout, PSTR("File type: '%c'\n"), *lit_mode);
  2573.     /* Read literal file name, use it if possible */
  2574.     litfile[0] = 0;
  2575.     fread (litfile,1,1,f); 
  2576.     if (is_ctb_type(ctb, CTB_LITERAL2_TYPE))
  2577.     {    /* subtract header length: namelength + lengthbyte + modebyte + stamp */
  2578.         LITlength -= litfile[0] + 2 + sizeof(dummystamp);
  2579.     }
  2580.     /* Use litfile if it's writeable and he didn't say an outfile */
  2581.     if (litfile[0] > 0)
  2582.     {    if ((int)litfile[0] >= MAX_PATH)
  2583.         {    fseek(f, litfile[0], SEEK_CUR);
  2584.             litfile[0] = 0;
  2585.         }
  2586.         else
  2587.             fread (litfile+1,1,litfile[0],f);
  2588.     }
  2589.     if (litfile[0])
  2590.     {    PascalToC( (char *)litfile );
  2591.         if (verbose)
  2592.             fprintf(pgpout, PSTR("Original plaintext file name was: '%s'\n"), litfile);
  2593.         if (preserved_name)
  2594.             strcpy(preserved_name, (char *) litfile);
  2595.     }
  2596.     if (*lit_mode == MODE_LOCAL) {
  2597.         fread(org_sys, 1, 4, f); org_sys[4] = '\0';
  2598. #ifdef VMS
  2599. #define LOCAL_TEST !strncmp("VMS ",org_sys,4)
  2600. #else
  2601. #define LOCAL_TEST FALSE
  2602. #endif
  2603.         if (LOCAL_TEST) {
  2604. #ifdef VMS
  2605.             remove(outfile);  /*  Prevent litter, we recreate the file with correct chars. */
  2606.             fread(&fdl_len, 2, 1, f);
  2607.             fdl = (char *) malloc(fdl_len);
  2608.             fread(fdl, 1, fdl_len, f);
  2609.             if ((g = fdl_create( fdl, fdl_len, outfile, (char *) litfile)) == NULL) {
  2610.                 fprintf(pgpout,"\n\007Unable to create file %s\n", outfile);
  2611.                 return(-1);
  2612.             }
  2613.             free(fdl);
  2614.             if (preserved_name)
  2615.                 strcpy(preserved_name, (char *) litfile);
  2616.             LITlength -= (fdl_len + sizeof(fdl_len));
  2617. #endif /* VMS */
  2618.         } else {
  2619.             fprintf(pgpout,"\n\007Unrecognised local binary type %s\n",org_sys);
  2620.             return(-1);
  2621.         }
  2622.     } else {
  2623.         /* Discard file creation timestamp for now */
  2624.         fread (&dummystamp, 1, sizeof(dummystamp), f);
  2625.     }
  2626.  
  2627.     if (*lit_mode==MODE_LOCAL) {
  2628. #ifdef VMS
  2629.         if (status = fdl_copyfile2bin( f, g, LITlength)) {   /*  Copy ok? */
  2630.             if (status > 0)
  2631.                 fprintf(stderr,"\n...copying to literal file\n");
  2632.             else
  2633.                 perror("\nError copying from work file");
  2634.             fdl_close(g);
  2635.             goto err1;
  2636.         }
  2637.         fdl_close(g);
  2638. #endif /*VMS */
  2639.     } else {
  2640.         if (*lit_mode == MODE_TEXT)
  2641.             g = fopen(outfile, FOPWTXT);
  2642.         else
  2643.             g = fopen(outfile, FOPWBIN);
  2644.         if (g == NULL)
  2645.         {    fprintf(pgpout, PSTR("\n\007Can't create plaintext file '%s'\n"), outfile );
  2646.             goto err1;
  2647.         }
  2648.         /* copy rest of literal plaintext file */
  2649.         CONVERSION = (*lit_mode == MODE_TEXT) ? EXT_CONV : NO_CONV;
  2650.         if (*lit_mode == MODE_BINARY)
  2651.             status = copyfile(f, g, LITlength);
  2652.         else
  2653.             status = copyfile_from_canon(f, g, LITlength);
  2654.         CONVERSION = NO_CONV;
  2655.         if (write_error(g) || status < 0)
  2656.         {    fclose(g);
  2657.             goto err1;
  2658.         }
  2659.         fclose(g);
  2660.     }
  2661.  
  2662.     fclose(f);
  2663.     return(0);    /* normal return */
  2664.  
  2665. err1:
  2666.     fclose(f);
  2667.     return(-1);    /* error return */
  2668.  
  2669. }    /* strip_literal */
  2670.  
  2671.  
  2672. /*======================================================================*/
  2673.  
  2674.  
  2675. int decryptfile(char *infile, char *outfile)
  2676. {
  2677.     byte ctb;    /* Cipher Type Byte */
  2678.     byte ctbCKE; /* Cipher Type Byte */
  2679.     FILE *f;
  2680.     FILE *g;
  2681.     int count = 0, status, thiskey, gotkey, end_of_pkes;
  2682.     unit n[MAX_UNIT_PRECISION], e[MAX_UNIT_PRECISION], d[MAX_UNIT_PRECISION];
  2683.     unit p[MAX_UNIT_PRECISION], q[MAX_UNIT_PRECISION], u[MAX_UNIT_PRECISION];
  2684.     byte inbuf[MAX_BYTE_PRECISION];
  2685.     byte outbuf[MAX_BYTE_PRECISION];
  2686.     byte keyID[KEYFRAGSIZE];
  2687.     word32 tstamp; byte *timestamp = (byte *) &tstamp;        /* key certificate timestamp */
  2688.     byte userid[256];
  2689.     word32 flen;
  2690.     word32 fpos = 0;
  2691.     byte ver, alg;
  2692.     short realprecision = 0;
  2693.     word16 chksum;
  2694.     struct nkey {
  2695.         byte keyID[KEYFRAGSIZE];
  2696.         struct nkey *next;
  2697.     } *nkey, *nkeys = NULL;
  2698.  
  2699.     if (verbose)
  2700.         fprintf(pgpout,"decryptfile: infile = %s, outfile = %s\n",
  2701.         infile,outfile);
  2702.  
  2703.     /* open file f for read, in binary (not text) mode...*/
  2704.     if ((f = fopen(infile,FOPRBIN)) == NULL)
  2705.     {    fprintf(pgpout,PSTR("\n\007Can't open ciphertext file '%s'\n"),infile);
  2706.         return(-1);
  2707.     }
  2708.  
  2709.     /* Now we have to keep reading in packets until we either get
  2710.      * to a non PKE-type packet or we find our own...  Once we find
  2711.      * our own, we're gonna have to get our private key, and then
  2712.      * keep going until we find the end of the PKE packets
  2713.      *
  2714.      * -derek    <warlord@MIT.EDU>    13 Dec 1992
  2715.      */
  2716.  
  2717.     gotkey = end_of_pkes = 0; /* Set this flag now. */
  2718.     do {
  2719.         thiskey = 0;
  2720.  
  2721.         set_precision(MAX_UNIT_PRECISION);
  2722.         /* Need to set this EACH TIME...   Sigh.  This is because
  2723.          * read_mpi needs to have a global_precision which is
  2724.          * >= the size of the key.  Therefore once we find the
  2725.          * real key, we save off the precision and then we'll
  2726.          * reset it later.    -derek
  2727.          */
  2728.  
  2729.         fread(&ctb,1,1,f);    /* read Cipher Type Byte */
  2730.         if (!is_ctb(ctb)) {
  2731.             fprintf(pgpout,PSTR("\n\007'%s' is not a cipher file.\n"),infile);
  2732.             fclose(f);
  2733.             return(-1);
  2734.         }
  2735.  
  2736.         /* PKE is Public Key Encryption */
  2737.         if (!is_ctb_type(ctb,CTB_PKE_TYPE)) {
  2738.             end_of_pkes = 1;
  2739.             continue;
  2740.         }
  2741.  
  2742.         getpastlength(ctb, f); /* read packet length */
  2743.  
  2744.         /* Read and check version */
  2745.         fread (&ver, 1, 1, f);
  2746.         if (version_error(ver, VERSION_BYTE))
  2747.             {    fclose (f);
  2748.                 return (-1);
  2749.             }
  2750.  
  2751.         fread(keyID,1,KEYFRAGSIZE,f); /* read key ID */
  2752.         /* Use keyID prefix to look up key. */
  2753.  
  2754.         /* Add this keyID to the list of keys read in */
  2755.         if ((nkey = (struct nkey *) malloc(sizeof(struct nkey))) 
  2756.             == NULL) {
  2757.             fprintf(stderr, PSTR("\n\007Out of memory.\n"));
  2758.             exitPGP(7);
  2759.         }
  2760.         memcpy(nkey->keyID, keyID, KEYFRAGSIZE);
  2761.         nkey->next = nkeys;
  2762.         nkeys = nkey;
  2763.  
  2764.         /* Read and check algorithm */
  2765.         fread (&alg, 1, 1, f);
  2766.         if (version_error(alg, RSA_ALGORITHM_BYTE))
  2767.             {    fclose (f);
  2768.                 return (-1);
  2769.             }
  2770.  
  2771.         if (!gotkey)        /* Only do this if we havent already */
  2772.             /*    Get and validate secret key from a key file: */
  2773.             if (getsecretkey(GPK_GIVEUP|(quietmode?0:GPK_SHOW),
  2774.                      NULL, keyID, timestamp, NULL, NULL,
  2775.                      userid, n, e, d, p, q, u) == 0)
  2776.                 {    
  2777.                     thiskey = gotkey = 1;
  2778.                     realprecision = global_precision;
  2779.                 } else {
  2780.                     set_precision(MAX_UNIT_PRECISION);
  2781.                 }                    
  2782.         /* DAMN this... This is REALLY frustrating, that I have to
  2783.          * do this...  Basically, if I go to getsecretkey, it will
  2784.          * set the precision, and the precision might NOT be correct
  2785.          * if the key I get is not correct, so I have to set the
  2786.          * precision NUMEROUS times in this loop..  This sucks, 
  2787.          * but its the only way.  Sigh.
  2788.          *
  2789.          * -derek    <warlord@MIT.EDU>    13 Dec 1992
  2790.          */
  2791.  
  2792.         /*    Note that RSA key must be at least big enough 
  2793.             to encipher a complete conventional key packet in 
  2794.             a single RSA block. */
  2795.  
  2796.         /*========================================================*/
  2797.         /* read ciphertext block, converting to internal format: */
  2798.         read_mpi((unitptr)inbuf, f, FALSE, FALSE);
  2799.  
  2800.         if (thiskey) {
  2801.             if (!quietmode) {
  2802.                 fprintf(pgpout,PSTR("Just a moment...")); 
  2803.                 /* RSA will take a while. */
  2804.                 fflush(pgpout);
  2805.             }
  2806.             count = rsa_private_decrypt(outbuf, (unitptr)inbuf,
  2807.                                         e, d, p, q, u, n);
  2808.             if (count < 0)
  2809.             {    fprintf(pgpout,
  2810. PSTR("\n\007Error: RSA-decrypted block is corrupted.\n\
  2811. This may be caused either by corrupted data or by using the wrong RSA key.\n"));
  2812.                 fclose(f);
  2813.                 return(-1);
  2814.             }
  2815.             if (!quietmode)
  2816.                 fputc('.',pgpout);    
  2817.                     /* Signal RSA completion. */
  2818.         }
  2819.  
  2820.         fpos = ftell(f);    /* Save this position */
  2821.  
  2822.     } while (!end_of_pkes);        /* Loop until end of PKE packets */
  2823.  
  2824.     /* Should we list the recipients? */
  2825.     if (!gotkey || verbose) {
  2826.         char *user;
  2827.  
  2828.         setkrent(NULL);
  2829.         init_userhash();
  2830.         if (gotkey)    /* verbose flag */
  2831.             fprintf(pgpout,"\nRecipients:\n");
  2832.         else
  2833.             fprintf(pgpout,PSTR("\nThis message can only be read by:\n"));
  2834.  
  2835.         for (nkey = nkeys; nkey; nkey = nkey->next) {
  2836.             if ((user = user_from_keyID(nkey->keyID)) == NULL)
  2837.                 fprintf(pgpout, "  keyID: %s\n", keyIDstring(nkey->keyID));
  2838.             else
  2839.                 fprintf(pgpout, "  %s\n", LOCAL_CHARSET(user));
  2840.         }
  2841.         endkrent();
  2842.     }
  2843.     for (nkey = nkeys; nkey; )
  2844.     {    nkey = nkey->next;
  2845.         free(nkeys);
  2846.         nkeys = nkey;
  2847.     }
  2848.  
  2849.     /* Ok, Now lets clean up, and continue on to the rest of the file so
  2850.      * that it can be decrypted properly.  Things should be ok once I
  2851.      * reset some stuff here...    -derek
  2852.      */
  2853.     if (gotkey)
  2854.     {
  2855.         fseek(f, fpos, SEEK_SET); /* Get back to the Real McCoy! */
  2856.         set_precision(realprecision); /* reset the precision */
  2857.     }
  2858.     else
  2859.     {    /* No secret key, exit gracefully (NOT!) */
  2860.         fprintf(pgpout, PSTR("\n\007You do not have the secret key needed to decrypt this file.\n"));
  2861.         fclose(f);
  2862.         return(-1);
  2863.     }
  2864.     /* Verify that top of buffer has correct algorithm byte */
  2865.     --count;    /* one less byte to drop algorithm byte */
  2866. /* Assume MSB external byte ordering */
  2867.     if (version_error(outbuf[0], IDEA_ALGORITHM_BYTE))
  2868.     {    fclose(f);
  2869.         return(-1);
  2870.     }
  2871.  
  2872.     /* Verify checksum */
  2873.     count -= 2;    /* back up before checksum */
  2874. /* Assume MSB external byte ordering */
  2875.     chksum = fetch_word16(outbuf+1+count);
  2876.     if (chksum != checksum(outbuf+1, count))
  2877.     {    fprintf(pgpout,PSTR("\n\007Error: RSA-decrypted block is corrupted.\n\
  2878. This may be caused either by corrupted data or by using the wrong RSA key.\n"));
  2879.         fclose(f);
  2880.         return(-1);
  2881.     }
  2882.  
  2883.     /* outbuf should contain random IDEA key packet */
  2884.     /*==================================================================*/
  2885.  
  2886.     /*     open file g for write, in binary (not text) mode... */
  2887.  
  2888.     if ((g = fopen( outfile, FOPWBIN )) == NULL)
  2889.     {    fprintf(pgpout, PSTR("\n\007Can't create plaintext file '%s'\n"), outfile );
  2890.         goto err1;
  2891.     }
  2892.  
  2893.     fread(&ctbCKE,1,1,f);    /* read Cipher Type Byte, should be CTB_CKE */
  2894.     if (!is_ctb(ctbCKE) || !is_ctb_type(ctbCKE,CTB_CKE_TYPE))
  2895.     {    /* Should never get here. */
  2896.         fprintf(pgpout,"\007\nBad or missing CTB_CKE byte.\n");
  2897.         goto err1;    /* Abandon ship! */
  2898.     }
  2899.  
  2900.     flen = getpastlength(ctbCKE, f); /* read packet length */
  2901.  
  2902.     /* Decrypt ciphertext file */
  2903. /* Assume MSB external byte ordering */
  2904.     status = idea_file( outbuf+1, DECRYPT_IT, f, g, flen );
  2905.     if (status < 0)
  2906.     {    fprintf(pgpout,PSTR("\n\007Error: Decrypted plaintext is corrupted.\n"));
  2907.     }
  2908.     if (!quietmode)
  2909.         fputc('.',pgpout);    /* show progress */
  2910.  
  2911.     if (write_error(g))
  2912.     {    fclose(g);
  2913.         goto err1;
  2914.     }
  2915.     fclose(g);
  2916.     fclose(f);
  2917.     burn(inbuf);    /* burn sensitive data on stack */
  2918.     burn(outbuf);    /* burn sensitive data on stack */
  2919.     mp_burn(d);    /* burn sensitive data on stack */
  2920.     mp_burn(p);    /* burn sensitive data on stack */
  2921.     mp_burn(q);    /* burn sensitive data on stack */
  2922.     mp_burn(u);    /* burn sensitive data on stack */
  2923.     if (status < 0)    /* if idea_file failed, then error return */
  2924.         return(status);
  2925.     return(1);    /* always indicate output file has nested stuff in it. */
  2926.  
  2927. err1:
  2928.     fclose(f);
  2929.     burn(inbuf);    /* burn sensitive data on stack */
  2930.     burn(outbuf);    /* burn sensitive data on stack */
  2931.     mp_burn(d);    /* burn sensitive data on stack */
  2932.     mp_burn(p);    /* burn sensitive data on stack */
  2933.     mp_burn(q);    /* burn sensitive data on stack */
  2934.     mp_burn(u);    /* burn sensitive data on stack */
  2935.     return(-1);    /* error return */
  2936.  
  2937. }    /* decryptfile */
  2938.  
  2939.  
  2940.  
  2941. int idea_decryptfile(char *infile, char *outfile)
  2942. {
  2943.     byte ctb;    /* Cipher Type Byte */
  2944.     FILE *f;
  2945.     FILE *g;
  2946.     byte ideakey[16];
  2947.     int status, retries = 0;
  2948.     struct hashedpw *hpw, **hpwp;
  2949.     word32 flen;
  2950.  
  2951.     if (verbose)
  2952.         fprintf(pgpout,"idea_decryptfile: infile = %s, outfile = %s\n",
  2953.         infile,outfile);
  2954.  
  2955.     /* open file f for read, in binary (not text) mode...*/
  2956.     if ((f = fopen(infile,FOPRBIN)) == NULL)
  2957.     {    fprintf(pgpout,PSTR("\n\007Can't open ciphertext file '%s'\n"),infile);
  2958.         return(-1);
  2959.     }
  2960.  
  2961.     /*     open file g for write, in binary (not text) mode... */
  2962.     if ((g = fopen( outfile, FOPWBIN )) == NULL)
  2963.     {    fprintf(pgpout, PSTR("\n\007Can't create plaintext file '%s'\n"), outfile );
  2964.         goto err1;
  2965.     }
  2966.  
  2967.     /* First, try all pre-specified passwords */
  2968.     hpwp = &passwds;
  2969.     hpw = *hpwp;
  2970.  
  2971.     do /* while pass phrase is bad */
  2972.     {
  2973.         fread(&ctb,1,1,f);    /* read Cipher Type Byte, should be CTB_CKE */
  2974.  
  2975.         if (!is_ctb(ctb) || !is_ctb_type(ctb,CTB_CKE_TYPE))
  2976.         {    /* Should never get here. */
  2977.             fprintf(pgpout,"\007\nBad or missing CTB_CKE byte.\n");
  2978.             fclose(g);
  2979.             goto err1;    /* Abandon ship! */
  2980.         }
  2981.         flen = getpastlength(ctb, f); /* read packet length */
  2982.  
  2983.         /* Get IDEA password, hashed */
  2984.         if (hpw)
  2985.         {    /* first try environment passwords */
  2986.             memcpy(ideakey, hpw->hash, sizeof(ideakey));
  2987.         }
  2988.         else
  2989.         {    fprintf(pgpout,PSTR("\nYou need a pass phrase to decrypt this file. "));
  2990.             if (batchmode || GetHashedPassPhrase((char *)ideakey,NOECHO1) <= 0)
  2991.             {    fclose(f);
  2992.                 fclose(g);
  2993.                 return(-1);
  2994.             }
  2995.         }
  2996.  
  2997.         if (!quietmode)
  2998.         {    fprintf(pgpout,PSTR("Just a moment..."));  /* this may take a while */
  2999.             fflush(pgpout);
  3000.         }
  3001.  
  3002.         status = idea_file( ideakey, DECRYPT_IT, f, g, flen );
  3003.         if (status == 0)
  3004.         {    if (hpw)
  3005.             {    /* "Use up" password. */
  3006.                 *hpwp = hpw->next;
  3007.                 memset(hpw->hash, 0, sizeof(hpw->hash));
  3008.                 free(hpw);
  3009.             }
  3010.             break;
  3011.         }
  3012.         if (hpw)
  3013.         {    /* Go to next available password */
  3014.             hpwp = &hpw->next;
  3015.             hpw = *hpwp;
  3016.         }
  3017.         else
  3018.         {    ++retries;
  3019.             fprintf(pgpout,PSTR("\n\007Error:  Bad pass phrase.\n"));
  3020.         }
  3021.  
  3022.         rewind(f);
  3023.         rewind(g);
  3024.     } while (status == -2 && retries < 2);
  3025.  
  3026.     burn(ideakey);    /* burn sensitive data on stack */
  3027.  
  3028.     if (status == 0 && !quietmode)
  3029.         fputc('.',pgpout);    /* show progress */
  3030.  
  3031.     if (write_error(g))
  3032.     {    fclose(g);
  3033.         goto err1;
  3034.     }
  3035.     fclose(g);
  3036.     fclose(f);
  3037.  
  3038.     if (status < 0)    /* if idea_file failed, then complain */
  3039.     {    remove(outfile);    /* throw away our mistake */
  3040.         return(status);        /* error return */
  3041.     }
  3042.     if (!quietmode)
  3043.         fprintf(pgpout,PSTR("Pass phrase appears good. "));
  3044.     return(1);    /* always indicate output file has nested stuff in it. */
  3045.  
  3046. err1:
  3047.     fclose(f);
  3048.     return(-1);    /* error return */
  3049.  
  3050. }    /* idea_decryptfile */
  3051.  
  3052.  
  3053.  
  3054. int decompress_file(char *infile, char *outfile)
  3055. {
  3056.     byte ctb;
  3057.     FILE *f;
  3058.     FILE *g;
  3059.     extern void lzhDecode( FILE *, FILE * );
  3060.     extern void unzip( FILE *, FILE * );
  3061.     if (verbose) fprintf(pgpout, PSTR("Decompressing plaintext...") );
  3062.  
  3063.     /* open file f for read, in binary (not text) mode...*/
  3064.     if ((f = fopen(infile,FOPRBIN)) == NULL)
  3065.     {    fprintf(pgpout,PSTR("\n\007Can't open compressed file '%s'\n"),infile);
  3066.         return(-1);
  3067.     }
  3068.  
  3069.     fread(&ctb,1,1,f);    /* read and skip over Cipher Type Byte */
  3070.     if (!is_ctb_type( ctb, CTB_COMPRESSED_TYPE ))
  3071.     {    /* Shouldn't get here, or why were we called to begin with? */
  3072.         fprintf(pgpout,"\007\nBad or missing CTB_COMPRESSED byte.\n");
  3073.         goto err1;    /* Abandon ship! */
  3074.     }
  3075.  
  3076.     getpastlength(ctb, f); /* read packet length */
  3077.     /* The packet length is ignored.  Assume it's huge. */
  3078.  
  3079.     fread(&ctb,1,1,f);    /* read and skip over compression algorithm byte */
  3080.     if (ctb != ZIP2_ALGORITHM_BYTE)
  3081.     {    /* We only know how to uncompress deflate-compressed data.  We
  3082.            may hit imploded or Lharc'ed data but treat it as an error just
  3083.            the same */
  3084.         fprintf(pgpout,PSTR("\007\nUnrecognized compression algorithm.\n\
  3085. This may require a newer version of PGP.\n"));
  3086.         goto err1;    /* Abandon ship! */
  3087.     }
  3088.  
  3089.     /*     open file g for write, in binary (not text) mode... */
  3090.     if ((g = fopen( outfile, FOPWBIN )) == NULL)
  3091.     {    fprintf(pgpout, PSTR("\n\007Can't create decompressed file '%s'\n"), outfile );
  3092.         goto err1;
  3093.     }
  3094.  
  3095.     unzip( f, g );
  3096.     if (verbose)
  3097.         fprintf(pgpout, PSTR("done.  ") );
  3098.     else if (!quietmode)
  3099.         fputc('.',pgpout);    /* show progress */
  3100.  
  3101.     if (write_error(g))
  3102.     {    fclose(g);
  3103.         goto err1;
  3104.     }
  3105.     fclose(g);
  3106.     fclose(f);
  3107.     return(1);    /* always indicate output file has nested stuff in it. */
  3108. err1:
  3109.     fclose(f);
  3110.     return(-1);    /* error return */
  3111.  
  3112. }    /* decompress_file */
  3113.  
  3114.